【问题标题】:Set selected value of DropDownList based on database根据数据库设置 DropDownList 的选定值
【发布时间】:2016-07-21 15:51:20
【问题描述】:

我在 gridview 中有一个下拉列表,当文本框发生更改时,我希望下拉列表中的选定值(总共三个单独的值)与数据库中的数据相匹配。文本框更改事件中的代码如下:

protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
        DropDownList ddl = new DropDownList();
        string connectionString = ConfigurationManager.ConnectionStrings["*******"].ConnectionString;
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            string query = "SELECT one, two, three FROM table WHERE id = " + TextBox1.Text;
            SqlDataAdapter sda = new SqlDataAdapter(query, con);
            DataSet ds = new DataSet();
            int num = sda.Fill(ds);
            if (num > 0)
            {
                GridView1.Visible = true;
                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
            else
            {
                if (num == 0)
                {
                    GridView1.Visible = false;
                }
                else
                {
                    BindGrid();
                }
            }
        }

【问题讨论】:

  • 您的设计容易受到 SQL 注入的影响。如果有人在TextBox1 中输入这个怎么办:“1; drop database DB_NAME()”。验证器并不能完全阻止这种情况,黑客可以修改 ViewState 来解决这个问题。
  • 文本框最多只能有十个字符,并且只允许整数。当您尝试输入任何其他内容时,它会提示您。而且我郑重发誓我会把它参数化,我只想让它先工作(两天而且还在继续)
  • 您的查询是否应该只返回一行?
  • 不可以返回多行
  • 如果它返回多行,哪些值会填充下拉列表?第一行的值?

标签: c# asp.net


【解决方案1】:

尝试使用RowDataBound 事件。为此,下拉列表必须已经填充了值,并且在这种情况下,SelectedValue 将被分配。

protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // this assumes the drop-down-list columns are the first, second, and third columns (ordinal positions 0, 1, and 2)
        DropDownList ddl1, ddl2, ddl3;
        ddl1 = (DropDownList)e.Row.Cells[0].Controls[0];
        ddl2 = (DropDownList)e.Row.Cells[1].Controls[0];
        ddl3 = (DropDownList)e.Row.Cells[2].Controls[0];
        DataRow currentRow = (DataRow)e.Row.DataItem;
        ddl1.SelectedValue = currentRow[0].ToString();
        ddl2.SelectedValue = currentRow[1].ToString();
        ddl3.SelectedValue = currentRow[2].ToString();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 2016-06-28
    相关资源
    最近更新 更多