2014-10-22 85 views
0

我有這個datagridView從一個對象獲取數據。 我添加列是這樣的:在datagridView中添加按鈕現在工作onClick事件

dataGridView1.CellClick += dataGridView1_CellClick; 
DataGridViewButtonColumn colUsers = new DataGridViewButtonColumn(); 
colUsers.UseColumnTextForButtonValue = true; 
colUsers.Text = "Users"; 
colUsers.Name = ""; 
dataGridView1.Columns.Add(colUsers); 

,然後加一個onclick事件,但它不工作,我失去了什麼?

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 

    if (e.RowIndex > -1 && dataGridView1.Columns[e.ColumnIndex].Name == "Users") 
    { 
     name = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString(); 
     gtUserDetails.ShowDialog(); 
    } 
} 

我收到一個錯誤:索引超出範圍。必須是非負數且小於集合的大小。

+0

檢查'ColumnIndex'和'RowIndex'在'CellClick'事件 – vallabha 2014-10-22 07:27:48

+0

我應該怎麼檢查? 如果我不添加新列,click事件可以工作,但不會與新的@vallabha – Perf 2014-10-22 07:29:11

+0

一樣,當您單擊添加了異常的按鈕正在引發或事件本身未觸發時。 – vallabha 2014-10-22 07:34:19

回答

1

您可以使用is運營商的檢查:「是你的其他按鈕」

,並使用CellContentClick代替CellClick,因爲如果你的按鈕填充用戶點擊,你的活動不提出並等待點擊你的按鈕。

爲此,您可以使用此事件

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) 
{ 
    if (dataGridView1[e.ColumnIndex,e.RowIndex] is DataGridViewButtonCell) 
     (dataGridView1[e.ColumnIndex, e.RowIndex] as DataGridViewButtonCell).Value = "You Clicked Me..."; 
} 
+0

謝謝,雖然有一個問題,我如何獲得所選行的第一列的值? – Perf 2014-10-22 08:02:24

+0

這是另一個問題,但我回答你聽到。你可以使用'dataGridView1.Rows [dataGridView1.SelectedCells [0] .RowIndex] .Cells [0] .Value =「Changed Me」;' – 2014-10-22 08:14:50

0

也許這是一個缺陷BUT:

colUsers.Name = ""; 

套的列名在一個空字符串,而不是 「用戶」。屬性Text與屬性Name不同。

colUsers.Name = "Users"; 

編輯:常量字符串

每當你想用你的代碼中的字符串值,PLZ開始使用恆定的參考。這將使您的字符串值保持在1位,而不是在錯誤信息給出可能性的情況下重複使用它們,從而導致錯誤的結果。

例如

const readonly string UserbuttonName = "Users"; 

private void CreatebuttonName() 
{ 
    colUsers.Name = UserbuttonName; 
} 

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
if (e.RowIndex > -1 && dataGridView1.Columns[e.ColumnIndex].Name == UserbuttonName) 
    DoSomething(); 
} 

編輯:性能

Datagridviewbutton列屬性的完整列表:http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewbuttoncolumn_properties(v=vs.110).aspx

+0

非常感謝你的解釋:) – Perf 2014-10-22 08:14:01