Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting value from a Gridview cell

I'm trying to get an int value from a GridView. Here is the screenshot of my gridview.

gridview screenshot

Here is the asp code for the Gridview

I have created a RowCommand method where when I press the Remove button on the GridView it is suppose to give me the int value of the 2nd column. So for example if I was to press the last Remove button it would give me an int value of 5.

This is my codebehind for the method

protected void grdOrder_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Remove")
    {

        int bigStore = Convert.ToInt32(grdOrder.SelectedRow.Cells[2].Text);

        clsStockCollection AnId = new clsStockCollection();

        clsStock TheOrder = new clsStock();
        TheOrder.OrderId = bigStore;
        AnId.DeleteOrder(TheOrder);
        DataCall();

    }
}

When I run this code I get this error. Object reference not set to an instance of an object.

I don't understand how or why I need to reference an object for example : Object As New Object. Why do I need to do this?

Here is the codebehind for the full class : pastebin.com/yzLR7s2w

A thanks in advance

like image 594
JARRRRG Avatar asked Mar 20 '13 00:03

JARRRRG


People also ask

How to get Cell Value in GridView?

Get cell value of GridView in RowCommand event in ASP.Net The row index can be easily determined using the CommandArgument property of GridViewCommandEventArgs object and using the row index, the GridView Row is referenced. Finally using the reference of the GridView Row, the values from the cells are fetched.

How do you find data from the grid?

We can get all the Grid Data in DataSource property of Grid in code behind. So, you can get all the Grid data in server edit event using DataSource property of Grid. Please refer to the below help document and code example. var data = this.


1 Answers

SelectedRows only returns rows that have been selected; without a selection you won't get anything. Instead of int bigStore = Convert.ToInt32(grdOrder.SelectedRow.Cells[2].Text); try:

int rowIndex = Convert.ToInt32(e.CommandArgument); // Get the current row
int bigStore = Convert.ToInt32(grdOrder.Rows[rowIndex].Cells[2].Text);
like image 75
Ryan Frame Avatar answered Oct 03 '22 09:10

Ryan Frame