2012-06-02 51 views
0

我想获取GridView的列的特定单元格值,但收到NullReferenceException错误。我不知道为什么,因为我正确使用所有控件并且使用正确的代码。请给我一个关于相同的解决方案。NullReferenceException从GridView获取特定的单元格值

代码:

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

我的网格视图:

enter image description here 在此先感谢。

+0

你检查什么行.Cells [0]包含? –

+0

你可以显示你的aspx代码 –

回答

1

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

否则,你需要检查row为空,因为没有保证,有一个选择的行当你的事件发生:

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