【问题标题】:How to populate a GridView drop-down list choices from SQL?如何从 SQL 填充 GridView 下拉列表选项?
【发布时间】:2014-04-02 09:30:13
【问题描述】:

这是我希望我的网格视图执行的操作。

My SQL 表 Pharmacy_Data 包含 Item_Name 和 Item_Code

从 Pharmacy_Data 表中填充 Item_Code。当我从下拉列表中选择项目名称时,它应该在字段中填写项目代码。

我该怎么做?

【问题讨论】:

  • 你能绑定网格并填充列吗?

标签: c# asp.net sql gridview datagridview


【解决方案1】:

1.将项目名称下拉列表的Autopostback设置为true,并在下拉列表更改事件中编写获取数据(项目代码)的代码并填写项目代码

【讨论】:

  • 我的网格视图目前不可见。
【解决方案2】:

请参阅以下Link.. 这可能会对您有所帮助。在链接中的示例中,他们使用直接值来使用列表填充下拉列表,而不是使用数据库来处理您的案例。

【讨论】:

    【解决方案3】:

    我通过向我的 GridView 添加 OnRowDataBound 函数解决了这个问题。

    OnRowDataBound="Grid_ItemList_RowDataBound"

    protected void Grid_ItemList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
        Connection con = new Connection();     
        if (e.Row.RowType == DataControlRowType.DataRow)
            {
    
            //Find the DropDownList in the Row
            DropDownList ddlnames = (e.Row.FindControl("ddlnames") as DropDownList);
            ddlnames.DataSource = con.GetData("Select Item_Code,Item_Name from mytable");
    
            //TextValue Pairs of DropDown list
            ddlnames.DataTextField = "Item_Name";
            ddlnames.DataValueField = "Item_Code";
            ddlnames.DataBind();
    
            //Add Default Item in the DropDownList
            ddlnames.Items.Insert(0, new ListItem("Please select"));
            }        
        }
    

    上面的代码提取了 ItemNames 和它们各自的 ItemCodes。

    现在,为了在选择时在文本框中显示代码,我为下拉元素使用了以下事件

    OnSelectedIndexChanged="ddlnames_OnChanged"

    protected void ddlnames_OnChanged(object sender, EventArgs e)
        {
        //Encapsulates the object back as a dropdown list
        DropDownList ddlnames = (DropDownList)sender;
    
        //Finds the control in the corresponding gridview row and edits the label
        GridViewRow row = (GridViewRow)ddlnames.NamingContainer;
        TextBox IC = (TextBox)row.FindControl("itemCode");
        IC.Text = ddlnames.SelectedValue; 
        }
    

    好吧,这就是我必须做的! :) 希望有一天有人会发现这很有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      • 2012-02-11
      • 1970-01-01
      相关资源
      最近更新 更多