C#DataGridView标题

时间:2013-12-10 18:26:29

标签: c# datagridview

首先,我对编程很感兴趣(第一周)。我有一个datagridviewer和CellClick事件。我的功能是什么,获取行的所选(鼠标左键单击)单元格的第一列值。 等;

ID名称地址(这是gridview的标题)

1 User1 Address1

2 User2 Address2

.. .. 6,7

9 User9 Address9

当您单击任何单元格时 - 除了标题 - 它会给出第一列的值。当您单击时,Address9您的值将返回为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
            { 

等。

2 个答案:

答案 0 :(得分: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
        { 

答案 1 :(得分: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);
  //...
}