下面的代碼說明了如何給datagridview添加按鈕列,以及點選相應按鈕做出不同反應的方法。
using System.Data;
using System.Data.Common;
namespace mydgv
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//綁定本來的資料,我這裡的資料已經為2列
dataGridView1.DataSource = GetDT();
//建立一個按鈕列
DataGridViewButtonColumn DGBC = new DataGridViewButtonColumn();
//是否用自定義的文本
DGBC.UseColumnTextForButtonValue = true;
DGBC.Text = "弄結果";
DGBC.Name = "Delete";
//添加按鈕列,這裡它是第3列了
dataGridView1.Columns.Add(DGBC);
//更改按鈕列标題
dataGridView1.Columns[2].HeaderText = "删除";
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//點吉的内容是哪一列
int CIndex = e.ColumnIndex;
//如果是第3列,也就是我們設定的按鈕列
if (CIndex == 2)
{
//得到是第幾行
int rowindex = e.RowIndex;
//得到該行其它格子的内容,
//我這裡是第2列格子的内容
string theid = dataGridView1.Rows[rowindex].Cells[1].Value.ToString();
//如果内容是 2
if (theid == "2")
{
label1.Text = "得到啦!";
return;
}
else
{
label1.Text = "~_~沒整着。!";
return;
}
}
}
//造幾個資料
DataTable GetDT()
{
DataTable mydt = new DataTable();
DataColumn dc0 = mydt.Columns.Add("ID", typeof(Int32));
DataColumn dc1 = new DataColumn();
mydt.Columns.Add(dc1);
for (int i = 0; i < 5; i++)
{
DataRow newRow = mydt.NewRow();
newRow[0] = "0";
newRow[1] = i;
//在最後面插入資料
mydt.Rows.Add(newRow);
}
return mydt;
}
}
}
在dataGridView1_CellContentClick這個事件中,
我們可以通過
//我這裡是第2列格子的内容
string theid = dataGridView1.Rows[rowindex].Cells[1].Value.ToString();
這個地方得到你想得到的任何資料,既然資料得到了,那麼就可以按自己的意願做事了。