使用下拉列表中的选定值更新Data GridView

时间:2018-04-19 13:52:09

标签: c# html asp.net

我有一个下拉列表和一个gridview ..下拉列表包含我在数据库中的表列表。我想要的是,当我从下拉列表中选择一个特定的表名时,我希望该特定表中的所有列和数据显示在gridview内。

这是我的代码...... 显示下拉列表中的表列表的代码是成功的..但是绑定gridview内的列和数据并不成功.. 请帮帮我......

protected void Page_Load(object sender, EventArgs e)
{
    using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True"))
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT table_name FROM INFORMATION_SCHEMA.TABLES", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        DropDownList1.DataSource = ds;
        DropDownList1.DataTextField = "table_name";
        DropDownList1.DataValueField = "table_name";
        DropDownList1.DataBind();
        con.Close();
    }
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True"))
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.columns where table_name='+ DropDownList1.selecteditem.text +'", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        //+DropDownList1.selecteditem.text +
        GridView1.DataBind();
        con.Close();
    }
}

1 个答案:

答案 0 :(得分:0)

这在几个层面上都是个坏主意。首先,您对SQL注入持开放态度。其次,您将为每个人提供对每个表的每个列和行的完全视图访问权限。

但是你没有获得数据的原因是因为select字符串没有意义。看起来应该是这样的

"SELECT * FROM INFORMATION_SCHEMA.columns where table_name='" + DropDownList1.SelectedValue + "'"

但这是正确的SQL连接应该是这样的。

//create a new datatable
DataTable dt = new DataTable();

//create the string that hold the query including token
string query = "SELECT * FROM INFORMATION_SCHEMA.columns where table_name = @TableName";

//create a new database connection
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
    command.CommandType = CommandType.Text;

    //replace the token with the correct value
    command.Parameters.Add("@TableName", SqlDbType.VarChar).Value = DropDownList1.SelectedValue;

    //open the connection
    connection.Open();

    //load the data of the select into the datatable
    dt.Load(command.ExecuteReader());

    //bind the datatable to the gridview
    GridView1.DataSource = dt;
    GridView1.DataBind();

    //but you can also skip the datatable and bind directly to the gridview
    GridView1.DataSource = command.ExecuteReader();
    GridView1.DataBind();
}