我有一个DataGridView
,其中显示了来自MS Access数据库的播放内容,此刻,我正试图了解如何分配每个按钮以执行不同的操作,例如显示新的表格或消息框。 / p>
此代码
private void btnShowPlays_Click(object sender, EventArgs e)
{
OleDbConnection myConnection = GetConnection();
try
{
myConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = myConnection;
string query = "select * from plays";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView.DataSource = dt;
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
dataGridView.Columns.Add(btn);
btn.HeaderText = "Options";
btn.Name = "More Info";
btn.Text = "More Info";
btn.UseColumnTextForButtonValue = true;
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Exception in DBHandler" + ex);
}
}
我尝试过
private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex==2)
{
MessageBox.Show((e.RowIndex+1).ToString() +" Information");
}
}
我认为这是有问题的,但是我想做的是让每一行上的每个按钮显示不同的表单或消息框。
答案 0 :(得分:1)
我认为可以通过以下方式解决您的问题:
private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var gridView = (DataGridView)sender;
if (gridView.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
e.RowIndex >= 0)
{
//TODO: Button was clicked. Check the index of the row and do you specialized work for different rows.
}
}
这是事件的代码,您必须将其绑定到数据网格,并使用rowIndex编写switch / if,以使每个按钮具有不同的功能。
希望有帮助!
在阅读了有关原始问题的其他注释和版本后添加的内容:
private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var gridView = (DataGridView)sender;
if (gridView.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
e.RowIndex >= 0)
{
string typeOfRow = gridView.Rows[e.RowIndex].Cells[2 /*Column that defines the type of action to take*/].ToString();
if (typeOfRow == "ShowMessage")
{
// Here i just copied the logic you added, dont know if it makes sense.
MessageBox.Show((e.RowIndex + 1).ToString() + " Information");
//I would assume you want to do this instead:
MessageBox.Show((gridView.Rows[e.RowIndex].Cells[3/*number of column with data to show*/]).ToString() + " Information");
}
}
}