DropDownList in GridView

Running Example:

Design the Page:
<div>
    <h1>Users List</h1>
    <asp:GridView ID="grdUsers" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="userName" HeaderText="User Name" />
        <asp:TemplateField>
            <HeaderTemplate>Country</HeaderTemplate>
            <ItemTemplate>
                <asp:DropDownList ID="cboCountryId" runat="server">
                    <asp:ListItem Text="México" Value="0"></asp:ListItem>
                    <asp:ListItem Text="USA" Value="1"></asp:ListItem>
                    <asp:ListItem Text="China" Value="2"></asp:ListItem>
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    </asp:GridView>
</div>

Adding the data to the GridView:
//DataTable
DataTable dt = new DataTable();
//Columns
DataColumn useName = dt.Columns.Add("userName", 
    Type.GetType("System.String"));
useName.AllowDBNull = false;
useName.Unique = true;
DataColumn countryId = dt.Columns.Add("countryId", 
    Type.GetType("System.Int32"));
countryId.AllowDBNull = false;
countryId.Unique = false;
//Add Data
DataRow dr = dt.NewRow();
dr["userName"] = "mx";
dr["countryId"] = "0";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["userName"] = "us";
dr["countryId"] = "1";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["userName"] = "cn";
dr["countryId"] = "2";
dt.Rows.Add(dr);
//BindData
grdUsers.DataSource = dt;
grdUsers.DataBind();

To ensure the correct selected item we need add the "onrowdatabound" event:

On the C# code, add the next code to ensure the correct selected item:
protected void grdUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow) {
        DropDownList cbo = (DropDownList)e.Row.FindControl("cboCountryId");
        //Select the value
        cbo.SelectedIndex = 
            cbo.Items.IndexOf(cbo.Items.FindByValue(DataBinder.
            Eval(e.Row.DataItem, "countryId").ToString()));
        cbo.Dispose();
    }
}

Now, if you wan to get the selected value to each row, you need use a loop, here an example:
Set the "DataKeyNames" propertie to the GridView:

Create a procedure to loop the GridView:
void GridLoop()
{
       
    try
    {
        for (int I = 0; I <= grdUsers.Rows.Count - 1; I++)
        {
            //Get the object
            DropDownList cbo = 
                (DropDownList)grdUsers.Rows[I].FindControl("cboCountryId");
            lblValues.Text += 
                String.Format("User Name: {0}<br />" +
                "Selected Text: {1}<br />" +
                "Selected Value: {2}<br />"+
                "<hr />",
                grdUsers.DataKeys[I].Value.ToString(),
                cbo.SelectedItem.Text,
                cbo.SelectedValue.ToString());
        }
    }
    catch (Exception ex)
    {
        throw (ex);
    }
}

The code to display the values:
protected void btnGetValues_Click(object sender, EventArgs e)
{
    try {
        GridLoop();
    }
    catch (Exception ex) {
        lblValues.Text = ex.Message;
    }
}

Full example:


Please Click on the +1 button

No hay comentarios:

Publicar un comentario