Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the value of particular row in gridview?

How can i find value of particular row in gridview. Say a gridview has 10 rows and 4 columns. I know that we can find the row number from row index, but how can we find what is the value of column 2 of row 5 (as per my gridview) or know a value of the cell?

like image 942
xorpower Avatar asked Jan 26 '26 05:01

xorpower


2 Answers

Use the following:

CustomersGridView.Rows[rowIndex].Cells[cellIndex].Text

More about .Rows collection

If you are interested in FindControl method, the most suitable event for you is RowDataBound:

void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        var control = e.Row.Cell[cellIndex].FindControl("ControlID");
        e.Row.Cells[1].Text = ((TypeOfControl)control).Text;
    }
}
like image 108
VMAtm Avatar answered Jan 28 '26 17:01

VMAtm


Assuming one cell per column this should do the trick:

string cellValue = GridView1.Rows[4].Cells[1].Text;

That would give you the value of column 2 at row 5.

Depending on how the row is built (if, for example, one column has a DropDownList or some other such control) you might be better off doing FindControl(controlID).

UPDATE

Say you have a DropDownList in the 2nd column with ID="ddlMyDropDown":

DropDownList ddl = (DropDownList)GridView1.Rows[4].FindControl("ddlMyDropDown");

Which event to put the code in depends on why you're trying to find the value. If you can give an example of when/why you'd need to get the value, we can tell you which event it should probably go in.

UPDATE 2

Assuming there's a button in the row, handle the RowCommand event:

protected void GridVie1_RowCommand(object sender, GridViewCommandEventArgs e)
{

    rowIndex = Convert.ToInt32(e.CommandArgument);

    DropDownList ddl = (DropDownList)GridView1.Rows[rowIndex].Cells[1].FindControl("ddlMyDropDown");

    // Do something
}

Do be cautious here, however, as the RowCommand is fired whenever a button in the row is clicked, so you'd need to make sure which button was clicked. You could use e.CommandName to get the CommandName of the button if you set it, but be aware that there are some predefined names.

See GridView.RowCommand Event for more information.

If you can update your question with some more information (i.e., why you need to get the value and what interaction with the GridView would start that process, like a button click) a more precise answer can be provided.

I'm about done for the night, but I'll check back on this thread tomorrow.

like image 31
Tim Avatar answered Jan 28 '26 19:01

Tim



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!