0

我有一個gridview和一個刪除按鈕Asp.net。刪除僅在從gridview中選擇一行時才起作用。我想通過使用戶更友好來防止網站崩潰。所以如果用戶沒有選擇一行並按刪除,它會通過標籤通知他們。會不會是SelectedVlueSelectedRow如何使用try和catch處理SelectedIndexOutOfRange?

這是我嘗試:

if (GridView1.SelectedValue == null) 
     { 

      int i = GridView1.SelectedIndex; 
      myDataSet.Tables["Records"].Rows[i].Delete(); 

      GridView1.DataSource = myDataSet; 
      GridView1.DataBind(); 
     } 
     else 
     { 
      Label5.Text = "Oops, please select a row"; 
     } 

回答

0

SelectedRownull沒有選擇行時。您也可以使用SelectedIndex != -1。但是無論如何,你正在檢查== null而不是!= null什麼是錯誤的邏輯。

if (GridView1.SelectedRow != null) 
{ 
    // ... 
} 
else 
{ 
    Label5.Text = "Oops, please select a row"; 
} 

if (GridView1.SelectedIndex != -1) 
{ 
    // ... 
} 
else 
{ 
    Label5.Text = "Oops, please select a row"; 
} 
+0

啊..謝謝。有效 :)。 – anonymous 2013-05-03 11:51:23

+0

哦,是的,我是。但你必須等待一定的時間來接受答案不要擔心:) – anonymous 2013-05-03 12:09:43

+0

你回答得太快了,並且stackoverflow不喜歡它哈哈 – anonymous 2013-05-03 12:10:13

0

你應該用這個代替代碼:

 if (GridView1.SelectedRow != null && GridView1.SelectedIndex != -1) 
     { 
      int i = GridView1.SelectedIndex; 
      myDataSet.Tables["Records"].Rows[i].Delete(); 

      GridView1.DataSource = myDataSet; 
      GridView1.DataBind(); 
     } 
     else 
     { 
      Label5.Text = "Oops, please select a row"; 
     } 
0

試試這個:

if(GridView.SelectedRow != null) 
{ 
    // proceed with your action 
} 
else 
{  
    Label5.Text = "Oops, please select a row"; 
}