Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net Gridview Itemtemplate Dropdownlist

I am using C# ASP.net, and relative new to it, and need to accomplish below.

In my VS2010 web application project I have webform with a Gridview which fetches the data from a table.

In the Grid, I have Commandfiled Button (column1) and Item template with Dropdownlist (column2).

Use case is, user first selects one listitem from 3 list items (H, L and M) and then selects command button.

I am not able to figure out how to extract selected listitem from a selected row

protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{

    GridViewRow row = GridView2.SelectedRow;
    Label4.Text = "You selected " + row.Cells[4].Text + "."; 
    Label5.Text = "You selected this list item from dropdownlist " + ???? ; 
}

Thanks in advance.

like image 307
user219628 Avatar asked May 17 '26 17:05

user219628


1 Answers

The GridViewRow object provides the method FindControl (as do all container controls) to get access to a control in the row by its id. For example, if your DropDownList has an id of MyDropDown, you could use the following to access its selected value:

GridViewRow row = GridView2.SelectedRow;
DropDownList MyDropDown = row.FindControl("MyDropDown") as DropDownList;
string theValue = MyDropDown.SelectedValue;
// now do something with theValue

This is the recommended method for accessing all controls in your GridView. You want to avoid doing things like row.Cells[#] as much as possible, because it easily breaks when you re-arrange or add/remove columns from your GridView.

like image 188
mellamokb Avatar answered May 20 '26 06:05

mellamokb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!