[英]C# DataGridView Header
首先,我對編程很陌生(第一周)。 我上面有一個datagridviewer和CellClick事件。 我的功能是獲取行的選定(鼠標左鍵單擊)單元格的第一列值。 喜歡;
ID名稱地址(這是gridview的標題)
1個用戶1地址1
2用戶2地址2
..6,7 ..
9用戶9地址9
當您單擊任何單元格(標題除外)時,它將給出第一列的值。 當您單擊Address9時,您的值將返回為9等。
單擊標題單元格時出現異常錯誤。 它返回-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
{
等等..
通過使用以下方法之一檢查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
{
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);
//...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.