0

当按下按钮时,我调用了这段代码:

protected void Button1_Click(object sender, EventArgs e)
{
    if (DropDownList1.SelectedItem.ToString() =="ER00 - File Header")
    {
        using (SqlConnection con = 
                   new SqlConnection(ConfigurationSettings.AppSettings["DBcon"]))
        {
            if (String.IsNullOrEmpty(TextBox_ID.Text.ToString()))
            {
                lbl_NoBatchID.Text = "Please enter BatchID!";
            }
            else
            {
                try
                {
                    SqlCommand sqlCommand = new SqlCommand(
                        "Select * from tbl_WinApps_FileHeader Where BatchID =" +
                        TextBox_ID.Text.ToString());

                    sqlCommand.Connection = con;
                    con.Open();
                    SqlDataReader read = sqlCommand.ExecuteReader();

                    GridView1.DataSource = read;
                    GridView1.DataBind();
                }
                catch (Exception)
                {                           
                }
            }
        }
    }
}

它是这样工作的:用户输入一个ID,然后当按下按钮时,它将在SQL中显示表格。

如果用户没有在文本框中输入任何内容,则会提示“请输入 BatchID!” 但在那之后,它就留在那儿,即使我已经输入了有效的身份证,它也不会清除。知道为什么吗?

4

3 回答 3

1

ASP.NET 页面有一个叫做 ViewState 的东西,它可以在请求之间维护控件的状态。您需要清除 GridView 的 DataSource 值并重新绑定它。

           if (String.IsNullOrEmpty(TextBox_ID.Text.ToString()))
            {
                lbl_NoBatchID.Text = "Please enter BatchID!";
                GridView1.DataSource=null;
                GridView1.DataBind();
            }
            else
            {

如果查找成功,您还想清除错误:

catch(Exception e){
}
lbl_NoBatchID.Text = "";

我还应该注意,您的空catch()文件会吞下您可能遇到的任何数据库或查找错误。

于 2013-03-15T02:05:23.683 回答
1
   protected void Button1_Click(object sender, EventArgs e)
{
   if (DropDownList1.SelectedItem.ToString() =="ER00 - File Header")
    {

        using (SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["DBcon"]))
        {
            if (String.IsNullOrEmpty(TextBox_ID.Text.ToString()))
            {
                lbl_NoBatchID.Text = "Please enter BatchID!";

            }
            else
            {
                try
                {

                    SqlCommand sqlCommand = new SqlCommand("Select * from tbl_WinApps_FileHeader Where BatchID =" + TextBox_ID.Text.ToString());
                    sqlCommand.Connection = con;
                    con.Open();
                    SqlDataReader read = sqlCommand.ExecuteReader();

                        GridView1.DataSource = read;
                        GridView1.DataBind();
                    lbl_NoBatchID.Text = "";
                }
                catch (Exception)
                {                           

                }

            }
        }

    }
于 2013-03-15T02:06:09.487 回答
0

在您的 Else 块中添加这行代码。

lbl_NoBatchID.Text = "";
于 2013-03-15T02:07:40.497 回答