我DataTable table
DataGridView dataGridView1
有几个文本和整数列。它们添加了:
DataTable table = new DataTable();
table.Columns.Add("Guest name", typeof(string));
table.Columns.Add("Guest_id", typeof(int));
table.Columns.Add("Room_id", typeof(int));
table.Columns.Add("Room", typeof(string));
table.Columns.Add("Reservation_id", typeof(int));
table.Columns.Add("Reservation date", typeof(DateTime));
table.Columns.Add("Start date", typeof(DateTime));
table.Columns.Add("End date", typeof(DateTime));
dataGridView1.DataSource = table;
然后将dataGridView1
的按钮添加到特定列:
DataGridViewButtonColumn editGuest = new DataGridViewButtonColumn();
DataGridViewButtonColumn editRoom = new DataGridViewButtonColumn();
DataGridViewButtonColumn editReservation = new DataGridViewButtonColumn();
DataGridViewButtonColumn deleteReservation = new DataGridViewButtonColumn();
editGuest.Name = "Edit guest";
editGuest.Text = "Edit";
editGuest.UseColumnTextForButtonValue = true;
editRoom.Name = "Edit room";
editRoom.Text = "Edit";
editRoom.UseColumnTextForButtonValue = true;
editReservation.Name = "Edit reservation";
editReservation.Text = "Edit";
editReservation.UseColumnTextForButtonValue = true;
deleteReservation.Name = "Delete reservation";
deleteReservation.Text = "Delete";
deleteReservation.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Insert(2, editGuest);
dataGridView1.Columns.Insert(5, editRoom);
dataGridView1.Columns.Insert(10, editReservation);
dataGridView1.Columns.Insert(11, deleteReservation);
所有数据都从数据库插入table
,看起来不错。现在我尝试点击(任意)按钮并从(任何)单元格中获取文本。 Tryed:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
{
if (e.ColumnIndex == 0)
{
string text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
MessageBox.Show(text);
}
}
}
始终获得"编辑"或"删除"消息无论Cell []中有哪个号码。似乎dataGridView1
只有里面的按钮,而不是表格。如何从table
单元格而不是dataGridView
获取价值?
答案 0 :(得分:0)
我的快速测试显示单元格中有值,可能需要选择不同的索引。
仅获取数据项(不包括未绑定列),请尝试使用DataGridViewRow的DataBoundItem
属性。当使用绑定到DataTable时,实际类型将是DataRowView。
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
if (e.RowIndex >= 0 && senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn)
{
var cellValues = Enumerable.Range(0, senderGrid.Columns.Count)
.Select(i => senderGrid[i, e.RowIndex].Value);
string text = String.Join("; ", cellValues);
MessageBox.Show(text);
var rw = senderGrid.Rows[e.RowIndex].DataBoundItem as DataRowView;
text = String.Join("; ", rw.Row.ItemArray);
MessageBox.Show(text);
}
}