简体   繁体   中英

How to populate a GridView drop-down list choices from SQL?

Here is what I want my Grid View to do.

My SQL table Pharmacy_Data contains Item_Name and Item_Code

Populate the Item_Code from Pharmacy_Data table. When I select the Item Name from the dropdown, It should fill the Item Code in the field.

我的网格

How do I go about this?

1.将Item name dropdownlist的Autopostback设置为true,并在dropdownlist change事件内写入用于获取数据(Item code)的代码并填写Item code

Refer to the following Link .. This might help you in this. In the example in the link they use direct value to fill the dropdown using list instead use database for your case.

I resolved this issue by adding a OnRowDataBound function to my GridView.

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"));
        }        
    }

The above code pulls the ItemNames and their respective ItemCodes.

Now, to display the codes in the textbox on selection, I used the below event for the dropdown element

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; 
    }

Well, that's what I had to do! :) Hope someone finds this useful someday.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM