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开发者_StackOverflow社区 row 5 (as per my gridview) or know a value of the cell?
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;
}
}
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.
If you know the value of a cell then we can find the row
protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[0].Text.Contains("sometext"))
{
//code here..
}
}
}
精彩评论