Design the GridView as follows.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None"
onrowdatabound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:DropDownList runat="server" ID="drItems"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
GridView contains two columns one is bound filed and the other field is a TemplateField where dropdown field is added.
Create the data table as follows to bind to the grid view.
private DataTable createBindDatatable()
{
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Country", typeof(string));
dt.Columns.Add("Nationality", typeof(string));
dt.Rows.Add("Chamara", "Sri lanaka", "Sri lanakan");
dt.Rows.Add("Sam", "America","American");
dt.Rows.Add("Jhon", "India","Indian");
dt.Rows.Add("Cater", "Pakistan","Pakistani");
dt.Rows.Add("Amanda", "Australia", "Australian");
return dt;
}
In the GridView Row bound event add the below code.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList DR = (DropDownList)e.Row.FindControl("drItems");
DR.DataSource = createDatatable();
DR.DataTextField = "Country";
DR.DataValueField = "Country";
DR.DataBind();
DR.Items.Insert(0, new ListItem("Select Below", "0"));
}
}
Finally bind the GridView.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = createDatatable();
GridView1.DataBind();
}
}
Saturday, December 15, 2012
How To Add DropDownList inside the GridView
Subscribe to:
Post Comments (Atom)
No comments:
Write comments