我有一个 DataGridView
对象:
dataGridView1.DataSource = an.peaks;
(an.peaks 是一个 List<Point>
对象。Point
类型有 3 个属性:x、y、z)
witch 在运行时生成下一个表:(显然我不能上传 Image
但是因为我是新用户所以我会尝试绘制它:)
____|_x__|_y__|_z__|[new column ]
____|_11_|_12_|_13_|[text/button] <==\
____|_20_|_30_|_40_|[text/button] <== } Add text if something or button if something else.
____|_50_|_60_|_70_|[text/button] <==/
我想在满足某些条件的每一行的新列中添加按钮(如图中所示)。如果不满足条件,则添加一些文本。
示例:如果点已经存在于数据库中,则显示它的物质名称(每个点代表一种物质)。如果不添加按钮“添加”到相应的行,将新点添加到数据库。
条件不是问题 - 它们仅用于示例。问题是将按钮/文本添加到每一行以及新按钮的点击事件。
最佳答案
这实际上使用 DataGridView
非常简单。你需要做的是:
添加 DataGridViewButtonColumn 类型的列
DataGridViewButtonColumn
是标准的 DataGridView
列类型。它可以通过设计器添加,但我通常更喜欢使用代码(通常在表单构造函数中)。
DataGridViewButtonColumn col = new DataGridViewButtonColumn();
col.UseColumnTextForButtonValue = True;
col.Text = "ADD";
col.Name = "MyButton";
dataGridView1.Columns.Add(col);
将 UseColumnTextForButtonValue
设置为 true 意味着 Text
属性将应用于所有按钮,为它们提供“ADD”按钮文本。您还可以使用 DataPropertyName
指向网格数据源中的列以提供按钮文本,或者您甚至可以直接设置每个单元格的值。
将按钮更改为文本
一旦你有了按钮列,你就想把特定的按钮变成文本。您可以通过将按钮类型的单元格替换为一种文本类型来执行此操作。您可以在很多地方这样做,但最好的地方之一是在 DataBindingComplete
事件处理程序中 - 一旦网格被绑定(bind)并准备好显示但在绘制之前,该事件就会触发。
下面我只是抓取索引为 1 的行,但您也可以检查每一行的 Value
属性。
void dataGridView1_DataBindingComplete(object sender,
DataGridViewBindingCompleteEventArgs e)
{
dataGridView1.Rows[1].Cells["MyButton"] = new DataGridViewTextBoxCell();
}
响应按钮点击
问题的最后一部分是响应按钮点击。这有点笨拙 - 您需要对整个网格使用 CellClick
事件或 EditingControlShowing
事件。
细胞点击
private void DataGridView1_CellClick(object sender, System.Windows.FormsDataGridViewCellEventArgs e) { if (DataGridView1.Columns[e.ColumnIndex].Name == "MyButton") { // button clicked - do some logic } }
编辑控件显示
void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { if (e.Control is Button) { Button btn = e.Control as Button; btn.Click -= new EventHandler(btn_Click); btn.Click += new EventHandler(btn_Click); } } void btn_Click(object sender, EventArgs e) { int col = this.dataGridView1.CurrentCell.ColumnIndex; int row = this.dataGridView1.CurrentCell.RowIndex; // Rest of the logic goes here! }
在您的情况下,编辑控件方法可能是最好的,因为它不会响应单击已替换为文本的按钮。此外,这种方式更像是您响应表单上任何其他按钮的方式。
关于c# - 将新列中的按钮添加到 DataGrid 中的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10769316/