[英]Extracting datagridview values C#
一种简单的方法是为您的 DataGridView 设置一个 DataSource,在下面的示例中使用了一个 DataTable,第三列使用表达式将前两列相加。
即使 DataGridView 在没有 DataSource 的情况下也能很好地工作,尤其是在您的情况下,它会更好地工作,因为它可以确保正确的类型和自动计算。
BindingSource
允许在不接触 DataGridView 的情况下访问您的数据。
public partial class Form1 : Form
{
private readonly BindingSource _bindingSource = new BindingSource();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_bindingSource.DataSource = DataTable();
dataGridView1.DataSource = _bindingSource;
dataGridView1.DataError += DataGridView1OnDataError;
}
private void DataGridView1OnDataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = true;
MessageBox.Show("Wrong type");
}
private DataTable DataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("Col1", typeof(int));
dt.Columns.Add("Col2", typeof(int));
dt.Columns.Add("Total", typeof(int)).Expression = "Col1 + Col2";
dt.Rows.Add(10, 10);
return dt;
}
private void CurrentButton_Click(object sender, EventArgs e)
{
if (_bindingSource.Current == null)
{
return;
}
var row = ((DataRowView)_bindingSource.Current).Row;
MessageBox.Show($"Total is {row.Field<int>("Total")}");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.