清晰的标签价值

时间:2013-03-15 02:02:13

标签: c# asp.net label

按下按钮时调用此代码:

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!”但在那之后,即使我已经输入了有效的ID,它也会保留在那里并且不会清除。知道为什么会这样吗?

3 个答案:

答案 0 :(得分: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()将吞下您可能获得的任何数据库或查找错误。

答案 1 :(得分: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)
                {                           

                }

            }
        }

    }

答案 2 :(得分:0)

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

lbl_NoBatchID.Text = "";