【问题标题】:NullReferenceException while getting particular cell value from GridView从 GridView 获取特定单元格值时出现 NullReferenceException
【发布时间】:2012-06-02 08:58:38
【问题描述】:

我正在尝试获取 gridview 列的特定单元格值,但收到 NullReferenceException 错误。我不知道为什么,因为我以正确的方式和正确的代码使用所有控件。请给我建议一个解决方案。

代码:

 protected void lnkedit_Click(object sender, EventArgs e)
    {
        // LinkButton btndetails = sender as  LinkButton;
        //GridViewRow gvrow = (GridViewRow)btndetails.NamingContainer;
        //lblID.Text = gvdetails.DataKeys[gvrow.RowIndex].Value.ToString();
        ////  lblCompanyName.Text = gvrow.Cells[1].Text;
        //txt_ComName.Text = gvrow.Cells[1].Text;
        //txt_ShortName.Text = gvrow.Cells[2].Text;
        //txt_email.Text = gvrow.Cells[3].Text;
        //txt_website.Text = gvrow.Cells[4].Text;
        string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:/ATTt/App_Data/eTimeTrackLite1.mdb;Persist Security Info=False;");
        OleDbConnection conn = new OleDbConnection(str);
        conn.Open();
        OleDbCommand cmd = new OleDbCommand();
        GridViewRow row = gvdetails.SelectedRow;


        string index = row.Cells[0].Text.ToString();  **/*Error occure on this line*/**

        cmd.CommandText = "select CompanyId from Companies where CompanyFName = '"+index+"'";
        // cmd.Parameters.AddWithValue("@CompanyId", Convert.ToInt32(lblID.Text));
        cmd.Connection = conn;
        OleDbDataAdapter da = new OleDbDataAdapter();
        DataSet ds = new DataSet();
        da.Fill(ds);
        DataTable dt = new DataTable();
        dt = ds.Tables[0];
        CompanyId = dt.Rows[0]["CompanyId"].ToString();
       // da.UpdateCommand = cmd;

       // cmd.ExecuteNonQuery();
        this.ModalPopupExtender1.Show();
    }

我的网格视图:

提前致谢。

【问题讨论】:

  • 你检查了 row.Cells[0] 包含的内容吗?

标签: c# asp.net gridview


【解决方案1】:

是否可以处理SelectedIndexChanged 事件而不是链接点击?如果是这样 - 只需按照此处的 MSDN 示例 - http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.selectedrow.aspx

否则您需要检查 row 是否为 null,因为无法保证在您的事件发生时存在选定的行:

GridViewRow row = gvdetails.SelectedRow;
if (row == null)
{
    // Probably display some text to a user asking to select a row
    return;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多