1

I want to insert some values from grid to db while clicking button submit. While using the given below code shows an error. The code is given below. Help me to find a proper solution.

Code:

protected void btnApprove_Click(object sender, EventArgs e)
   {
        ShadingAnalysisDataSetTableAdapters.tbl_ItemRequest_StatusTableAdapter rs;
        rs = new ShadingAnalysisDataSetTableAdapters.tbl_ItemRequest_StatusTableAdapter();

        var ItemName = (Label)GridView2.SelectedRow.Cells[1].FindControl("lblItem");
        var Quantity = (Label)GridView2.SelectedRow.Cells[2].FindControl("lblQnty"); 

        rs.testInsert(ItemName, Quantity);
   }

I have modified my code based on the above suggestions. But now I am getting another error. The new error is: Object reference not set to an instance of an object.

enter image description here

Rahul Nikate
  • 6,192
  • 5
  • 42
  • 54
Vipin
  • 261
  • 6
  • 20
  • 44

3 Answers3

2

By doing this

var ItemName = (Label)GridView2.SelectedRow.Cells[1].FindControl("lblItem");

ItemName would be a Label instead of the text value of lblItem. I would guess that both parameters of rs.testInsert method are string so you got the error because you're passing two Labels instead of two strings. You can get the text value from the .Text property of the label as below

var ItemName = ((Label)GridView2.SelectedRow.Cells[1].FindControl("lblItem")).Text;
var Quantity = ((Label)GridView2.SelectedRow.Cells[2].FindControl("lblQnty")).Text; 
ekad
  • 14,436
  • 26
  • 44
  • 46
2

You are finding Label control and assigning to var ItemName and var Quantity.So You are getting error "cannot convert from 'System.Web.UI.WebControls.Label' to 'string'".

 var ItemName = (Label)GridView2.SelectedRow.Cells[1].FindControl("lblItem");
 var Quantity = (Label)GridView2.SelectedRow.Cells[2].FindControl("lblQnty");

So, Add Text property to label.

 var ItemName = ((Label)GridView2.SelectedRow.Cells[1].FindControl("lblItem")).Text;
 var Quantity = ((Label)GridView2.SelectedRow.Cells[2].FindControl("lblQnty")).Text; 
Rahul Nikate
  • 6,192
  • 5
  • 42
  • 54
2
var ItemName = (Label)GridView2.SelectedRow.Cells[1].FindControl("lblItem");

here you will get the label control on the ItemName and you can get the label text value on string variable as given below.

string Text_Value= ItemName.text;
Steven
  • 2,437
  • 5
  • 32
  • 36
Manu Nair
  • 314
  • 2
  • 7