You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让TextMode=Date的TextBox自动获取次日日期用于GridView筛选?

问题解答

一、获取次日日期的实现(完全可行)

你要的需求可以直接实现,在txtTime_TextChanged事件中处理日期计算即可:

protected void txtTime_TextChanged(object sender, EventArgs e)
{
    // 解析用户选中的日期
    if (DateTime.TryParse(txtTime.Text, out DateTime selectedDate))
    {
        // 将选中日期存入标签
        lblTIME.Text = selectedDate.ToString("yyyy-MM-dd");
        // 计算次日日期并存入指定标签
        DateTime tomorrowDate = selectedDate.AddDays(1);
        lblTomorrow.Text = tomorrowDate.ToString("yyyy-MM-dd");
        
        // 执行GridView数据绑定
        BindScheduleData();
    }
}

二、SQL语句的错误修正(原写法不可行)

你给出的修改后SQL存在语法和逻辑错误,必须调整:

  1. ORDERY是拼写错误,正确写法为ORDER BY
  2. WHERE子句逻辑混乱,Date = 'xxx' AND 'yyy'属于无效条件,若要查询选中日期和次日的数据,应使用OR连接两个日期条件
  3. 直接拼接字符串会引发SQL注入风险,必须用参数化查询替代

修正后的参数化SQL代码:

private void BindScheduleData()
{
    // 确保日期解析有效
    if (DateTime.TryParse(lblTIME.Text, out DateTime selectedDate) && 
        DateTime.TryParse(lblTomorrow.Text, out DateTime tomorrowDate))
    {
        string sql = "SELECT * FROM Schedule.dbo WHERE Date = @SelectedDate OR Date = @TomorrowDate ORDER BY Date ASC";
        SqlCommand cmdSQL = new SqlCommand(sql);
        // 添加参数,避免SQL注入
        cmdSQL.Parameters.AddWithValue("@SelectedDate", selectedDate);
        cmdSQL.Parameters.AddWithValue("@TomorrowDate", tomorrowDate);
        
        GvSchedule.DataSource = MyRstP(cmdSQL);
        GvSchedule.DataBind();
    }
}

三、关键注意事项

  • SQL注入防护:绝对不要直接将用户输入拼接进SQL语句,参数化查询是必须的安全规范
  • 日期格式一致性:确保数据库Date字段的格式与代码中转换的日期格式一致(推荐使用yyyy-MM-dd)
  • 异常处理:必须判断用户是否选择了有效日期,避免日期解析失败导致程序报错

内容的提问来源于stack exchange,提问作者ServalChan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 22:10:43