3

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir for the solution and tip on avoiding cell index

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.