在Webform中显示SQL Server表数据

时间:2018-12-11 14:09:16

标签: c# sql-server ado.net

我有一个应用程序,该应用程序应允许用户从数据库中的表中查看宠物。

网页表单设计和Pets数据表的图片: Picture of web form design and Pets data table

这是我的按钮代码:

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给我看一下这个品种的宠物(包含大部分信息)...然后,我希望它为SpeciesSanctuary ...

工作

当前,当我选择一个品种并单击查看动物时,没有任何反应,如下图所示:

选择“房屋”品种并单击“查看动物”按钮后的网络表单图片: Picture of web form after selection of 'House' breed and click of view animals button

如何使它工作?

2 个答案:

答案 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());
    }
}