我有一个应用程序,该应用程序应允许用户从数据库中的表中查看宠物。
这是我的按钮代码:
protected void viewAnimalsBreedButton_Click(object sender, EventArgs e)
{
try
{
SqlConnection cnn = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\FrendsWithPaws.mdf;Integrated Security=True");
cnn.Open();
SqlCommand command = new SqlCommand("SELECT PetID, Breed, Name, Age, Gender, Picture, Sanctuary FROM Pets WHERE Breed='+ breedDropDownList.SelectedValue +'", cnn);
SqlDataReader reader = command.ExecuteReader();
petsGridView.DataSource = reader;
petsGridView.DataBind();
cnn.Close();
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
首先,我为宠物品种设置了一个dropdownlist
,当我在breed
中选择一个dropdown
并单击查看动物时,我希望gridview
给我看一下这个品种的宠物(包含大部分信息)...然后,我希望它为Species
和Sanctuary
...
当前,当我选择一个品种并单击查看动物时,没有任何反应,如下图所示:
如何使它工作?
答案 0 :(得分:2)
首先,您应始终使用parameterized queries来避免SQL Injection并摆脱此类问题。
其次,您需要创建一个DataTable
并通过数据读取器填充并将表绑定到网格:
cnn.Open();
SqlCommand command = new SqlCommand("SELECT PetID, Breed, Name, Age, Gender, Picture, " +
"Sanctuary FROM Pets where Breed = @Breed ", cnn);
command.Parameters.AddWithValue("@Breed", breedDropDownList.SelectedValue);
DataTable table = new DataTable();
table.Load(command.ExecuteReader());
petsGridView.DataSource = table;
petsGridView.DataBind();
cnn.Close();
尽管直接指定类型,并且使用Value属性比AddWithValue
更好。 https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
答案 1 :(得分:0)
您必须先将读取的数据加载到datatable
:
protected void viewAnimalsBreedButton_Click(object sender, EventArgs e)
{
try
{
SqlConnection cnn = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\FrendsWithPaws.mdf;Integrated Security=True");
cnn.Open();
SqlCommand command = new SqlCommand("SELECT PetID, Breed, Name, Age, Gender, Picture, Sanctuary FROM Pets WHERE Breed='" + breedDropDownList.SelectedValue + "'", cnn);
SqlDataReader reader = command.ExecuteReader();
var dataTable = new DataTable();
dataTable.Load(dataReader);
petsGridView.DataSource = dataTable;
petsGridView.DataBind();
cnn.Close();
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}