无法转换为System.Web.UI.WebControls.Label'到'字符串'?

时间:2014-12-01 04:27:23

标签: c# asp.net string gridview label

我想在点击按钮提交时从网格到数据库插入一些值。使用下面给出的代码显示错误。代码如下。帮我找一个合适的解决方案。

代码:

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);
   }

我已根据上述建议修改了我的代码。但是现在我又收到了另一个错误。新错误是:Object reference not set to an instance of an object.

enter image description here

3 个答案:

答案 0 :(得分:2)

通过这样做

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

ItemName将是Label而不是lblItem的文本值。我猜想rs.testInsert方法的两个参数都是字符串,所以你得到了错误,因为你传递了两个标签而不是两个字符串。您可以从标签的.Text属性获取文本值,如下所示

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

答案 1 :(得分:2)

您正在查找Label控件并分配给var ItemName和var Quantity.So您收到错误"无法转换为' System.Web.UI.WebControls.Label'到'字符串'"。

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

因此,将Text属性添加到标签。

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

答案 2 :(得分:2)

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

在这里,您将获得ItemName上的标签控件,您可以在字符串变量上获取标签文本值,如下所示。

string Text_Value= ItemName.text;