2013-12-10 48 views
1

首先,我在編程(第一週)方面很新穎。我有一個datagridviewer和CellClick事件。我的函數做的是,獲取行的選定(鼠標左鍵單元格)單元格的第一列值。 喜歡;C#DataGridView標題

ID名稱地址(此者的GridView的集管)

1 User1的地址1

2用戶2地址2

..6,7 ..

9 USER9 Address9

當你點擊任何單元格時 - 除了標題 - 它會給出第一列的值。當您點擊時,地址9您的值將返回爲9等。

單擊標題單元格時出現Outofexception錯誤。它返回-1值並崩潰。所以,我需要一個if語句來忽略標頭點擊。我在網站上搜索它,並且自己嘗試了很多東西,但沒有設法實現這一點。

private void dgwCust_CellClick(object sender, DataGridViewCellEventArgs e)  
{    

if (cellclick == isn't a header click?..) 

      string search; 
      search = dgwCust.Rows[e.RowIndex].Cells[0].Value.ToString();//this is where error comes in 
      SqlCommand cmdsearch = new SqlCommand("Select * from Customers where CustomerID = '" + search + "'", dbConnection); 
      try 
      { 

等。

+1

Metro?的WinForms? WPF? Silverlight的? Windows Phone? ASP.Net? MonoTouch的? – SLaks

+0

WinForms,但問題已解決。謝謝。 –

回答

2

檢查e.RowIndex不等於-1,使用以下

if (!e.RowIndex.Equals(-1)) 

if (e.RowIndex != -1) 

一個 -

private void dgwCust_CellClick(object sender, DataGridViewCellEventArgs e)  
{    

    if (!e.RowIndex.Equals(-1)) 

     string search; 
     search = dgwCust.Rows[e.RowIndex].Cells[0].Value.ToString();//this is where error comes in 
     SqlCommand cmdsearch = new SqlCommand("Select * from Customers where CustomerID = '" + search + "'", dbConnection); 
     try 
     { 
+0

謝謝。它工作。 –

0
if (e.RowIndex >= 0) 
{ 
    string search; 
    search = dgwCust.Rows[e.RowIndex].Cells[0].Value.ToString();//this is where error comes in 
    SqlCommand cmdsearch = new SqlCommand("Select * from Customers where CustomerID = '" + search + "'", dbConnection); 
    //... 
} 
+0

也謝謝! –

相關問題