我有一个dataGridView,其第一列包含复选框。现在根据我的要求,我必须得到Employee No
列的值,该行的复选框已被点击另一个按钮点击事件。还有如何获取多个复选框的值被选中。
这是我的代码..
private void btn_load_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Select", System.Type.GetType("System.Boolean"));
dt.Columns.Add("Employee No");
dt.Columns.Add("Employee Name");
dt.Columns.Add("Join Date");
DataRow dr;
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr["Select"] = false;
dr["Employee No"] = 1000 + i;
dr["Employee Name"] = "Employee " + i;
dr["Join Date"] = DateTime.Now.ToString("dd/MM/yyyy");
dt.Rows.Add(dr);
}
dataGridView1.AllowUserToAddRows = true;
dataGridView1.AllowUserToDeleteRows = true;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.DataSource = dt;
}
private void btn_Click(object sender, EventArgs e)
{
//I need the Employee Id values here
}
请帮帮我。谢谢。
答案 0 :(得分:2)
您还可以使用DataSource属性:
private void btn_Click(object sender, EventArgs e)
{
int[] employeeIds = (dataGridView1.DataSource as DataTable).Rows
.Cast<DataRow>()
.Where(r => (bool)r["Select"])
.Select(r => Convert.ToInt32(r["Employee No"]))
.ToArray();
}
并使用System.Linq命名空间。
答案 1 :(得分:1)
因为您已将DataTable绑定到网格DataSource,所以可以使dt
成为类变量并使用它来检查选定的变量。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private DataTable dt;
private void btn_load_Click(object sender, EventArgs e)
{
dt = new DataTable();
dt.Columns.Add("Select", System.Type.GetType("System.Boolean"));
dt.Columns.Add("Employee No");
dt.Columns.Add("Employee Name");
dt.Columns.Add("Join Date");
DataRow dr;
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr["Select"] = false;
dr["Employee No"] = 1000 + i;
dr["Employee Name"] = "Employee " + i;
dr["Join Date"] = DateTime.Now.ToString("dd/MM/yyyy");
dt.Rows.Add(dr);
}
dataGridView1.AllowUserToAddRows = true;
dataGridView1.AllowUserToDeleteRows = true;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.DataSource = dt;
}
private void btn_Click(object sender, EventArgs e)
{
//I need the Employee Id values here
foreach (DataRow row in dt.Rows)
{
if ((bool)row["Select"] == true)
{
}
}
}
}
答案 2 :(得分:1)
假设在表单类中声明为
的全局变量List<int> empIDs = new List<int> empIDs();
现在,您可以在点击事件中编写
private void btn_Click(object sender, EventArgs e)
{
empIDs.Clear();
foreach(DataGridViewRow r in dgv.Rows)
{
DataGridViewCheckBoxCell c = r.Cells["Select"] as DataGridViewCheckBoxCell;
if(Convert.ToBoolean(c.Value))
empIDs.Add(Convert.ToInt32(r.Cells["Employee No"].Value));
}
}
在click事件结束时,全局变量将填充单击其SELECT单元格的员工的ID