简体   繁体   中英

binding datatable multiple rows data to DropDownList

From my database I am retriving data table like below after making a query to DB. I my asp.net web form application I am having GridView and it is having BoundField and DropDownList.

I want to bind LectureID to the BoundField and subjects of pariculat lecture into DropDownList.

Have no idea how to do the required binging.

LectureID   SubjectName
1           Sub1
1           Sub2
1           Sub3
1           Sub4
2           Sub1
2           Sub4
 <asp:GridView ID="grdvDetail" runat="server">
    <Columns>
        <asp:BoundField HeaderText="LectureID" DataField="LectureID" SortExpression="LectureID">
            <HeaderStyle HorizontalAlign="Center" />
            <ItemStyle Font-Size="11px" />
        </asp:BoundField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:DropDownList ID="ddlSubject" runat="server">
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>



protected void Page_Load(object sender, EventArgs e)
{   
    if (!IsPostBack)
    {
        DataTable dt = new DataTable();
        //Fill DataTable Using SQL Query
        grdvDetail.DataSource = dt;
        grdvDetail.DataBind();

        for (int i = 0; i < grdvDetail.Rows.Count; i++)
        {
            DropDownList ddlSubject = ((DropDownList)grvProduct.Rows[i].FindControl("ddlSubject"));

            DataTable dtDDL = new DataTable();
            //Fill DataTable Using SQL Query
            ddlSubject.DataSource = dtDDL;
            ddlSubject.DataTextField = "SubjectName";
            ddlSubject.DataValueField = "SubjectName";
            ddlSubject.DataBind();
        }
    }
}

May be it is not perfect solution. Idea is to create a Key, Value collection from given datatable.

A Dictionary collection is used to keep lecture id as Key and related subjects in a List<string> as Value .

GridView is bind with Dictionary and in RowDataBound event of GridView each dropdownlist is populated as required.

Markup :

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            onrowdatabound="GridView1_RowDataBound">
      <Columns>
            <asp:BoundField DataField="Key" HeaderText="Lecture ID" />

            <asp:TemplateField HeaderText="Subject Name">
                <ItemTemplate>                            
                     <asp:DropDownList ID="ddlSubject" runat="server" >
                     </asp:DropDownList>
                </ItemTemplate>
             </asp:TemplateField>
      </Columns>
</asp:GridView>

Code Behind :

protected void Page_Load(object sender, EventArgs e)
{   
    if (!IsPostBack)
    {
         //test data
         DataTable dt = new DataTable();
         dt.Columns.Add("LectureID", typeof(int));
         dt.Columns.Add("SubjectName");

         dt.Rows.Add(1, "Sub1");
         dt.Rows.Add(1, "Sub2");
         dt.Rows.Add(1, "Sub3");
         dt.Rows.Add(1, "Sub4");

         dt.Rows.Add(2, "Sub1");
         dt.Rows.Add(2, "Sub4");              
         dt.AcceptChanges();               

         //Bind with GridView with Dictionary collection
         GridView1.DataSource = GetDictionary(dt);
         GridView1.DataBind();
    }
}

//get a dictionary of distinct lectureID
private Dictionary<int, List<string>> GetDictionary(DataTable dt)
    {
        var dictionary = new Dictionary<int, List<string>>();
        foreach (DataRow dr in dt.Rows)
        {
            int iKey = Convert.ToInt32(dr["LectureID"]);

            if (dictionary.ContainsKey(iKey))
            {
                List<string> lst = dictionary[iKey] as List<string>;
                lst.Add(dr["SubjectName"].ToString());
                dictionary[iKey] = lst;
            }
            else
            {
                var lst = new List<string>();
                lst.Add(dr["SubjectName"].ToString());
                dictionary.Add(iKey, lst);
            }
        }
        return dictionary;
    }

Row Data Bound Event :

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow &&
            e.Row.DataItem != null)
        {
            DropDownList ddl = e.Row.FindControl("ddlSubject") as DropDownList;
            ddl.DataSource = ((KeyValuePair<int, List<string>>)e.Row.DataItem).Value;
            ddl.DataBind();
        }
    }

Result Distinct LectureID with respective Subjects in DropDownList :

在此处输入图片说明

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