C# Sql命令不使用';t显示表
我有一个代码隐藏按钮,当按下按钮时,它会以SQL显示表格。 我似乎不知道这个问题,为什么它没有显示任何表格 我添加这行代码是为了检查BatchID是否超出sql表中的范围C# Sql命令不使用';t显示表,c#,asp.net,C#,Asp.net,我有一个代码隐藏按钮,当按下按钮时,它会以SQL显示表格。 我似乎不知道这个问题,为什么它没有显示任何表格 我添加这行代码是为了检查BatchID是否超出sql表中的范围 if (read.Read()) { GridView1.DataSource = read; GridView1.DataBind(); } else { lbl_NoBatchID.Text = "BatchID out of range
if (read.Read())
{
GridView1.DataSource = read;
GridView1.DataBind();
}
else
{
lbl_NoBatchID.Text = "BatchID out of range";
}
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
{
lbl_NoBatchID.Text = "";
SqlCommand sqlCommand = new SqlCommand("Select * from tbl_WinApps_FileHeader Where BatchID =" + TextBox_ID.Text.ToString());
sqlCommand.Connection = con;
con.Open();
SqlDataReader read = sqlCommand.ExecuteReader();
if (read.Read())
{
GridView1.DataSource = read;
GridView1.DataBind();
}
else
{
lbl_NoBatchID.Text = "BatchID out of range";
}
}
catch (Exception)
{
}
}
}
}
确保你做两件事 1.)在
Databind()之后关闭DataReader
2.)为您的GridView设置AutoGenerateColumns=“True”
,以供参考,您在该代码中有一些坏习惯。永远不要忽略异常——当你发现问题并修复它时,你会喜欢它。另外,您的SqlCommand
和SqlDataReader
需要在中使用
块。这甚至不能回答我的问题question@user1954418:您必须在问题中提供更多信息,尝试将catch
块更改为:catch(异常exc)
然后将代码放入捕获
块:MessageBox.Show(例如Message);硬编码命令文本中的参数是一个非常糟糕的主意,而且您的代码很容易被sql注入。尝试使用以避免此类攻击,还有一件小事-如果将“if”更改为if(DropDownList1.SelectedItem.ToString()!=“ER00-File Header”){return;}