我有一个带有预定义列的DGV,如下所示,这里是生成方法和绑定方法
fixGridAlarm(dgvAlarmlar);
public void fixGridAlarm(DataGridView gvw)
{
gvw.AutoGenerateColumns = false;
gvw.RowTemplate.Height = 75;
gvw.ColumnCount = 3;
gvw.Columns[0].Name = "No";
gvw.Columns[0].Width = 60;
gvw.Columns[0].ReadOnly = true;
gvw.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
gvw.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
gvw.Columns[1].Name = "Tarih/Saat";
gvw.Columns[1].Width = 490;
gvw.Columns[1].ReadOnly = true;
gvw.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
gvw.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
gvw.Columns[2].Name = "Açıklama";
gvw.Columns[2].Width = 1195;
gvw.Columns[2].ReadOnly = true;
gvw.Columns[2].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
gvw.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
BindAlarmlarGrid();
}
public void BindAlarmlarGrid()
{
string CSVFilePathName = pathAlarms;
string[] Lines = File.ReadAllLines(CSVFilePathName);
string[] Fields;
DataTable dt = new DataTable();
dt.Columns.Add(dgvAlarmlar.Columns[0].Name, typeof(int));
dt.Columns.Add(dgvAlarmlar.Columns[1].Name, typeof(DateTime));
dt.Columns.Add(dgvAlarmlar.Columns[2].Name, typeof(string));
DataRow Row;
for (int i = 0; i < Lines.GetLength(0); i++)
{
Fields = Lines[i].Split(new char[] { ',' });
Row = dt.NewRow();
for (int f = 0; f < 3; f++)
{
Row[f] = Fields[f];
}
dt.Rows.Add(Row);
}
dgvAlarmlar.DataSource = dt;
当我将DataSource
作为DataTable
列添加到原始DGV旁边时,如何将其绑定在原始网格上而不是下一个?
答案 0 :(得分:1)
数据绑定要求您设置DataGridViewColumn.DataPropertyName属性,如MSDN文档的备注部分所述:
当AutoGenerateColumns属性设置为true时,每列都会自动将其DataPropertyName属性设置为DataSource属性指定的数据源中的属性或数据库列的名称。此绑定也可以手动执行,当您只想显示数据源中可用的属性或数据库列的子集时,这非常有用。在这种情况下,将AutoGenerateColumns属性设置为false,然后手动添加每个DataGridViewColumn,将每个DataPropertyName属性的值设置为要显示的数据源中的属性或数据库列。
您可以使原始代码正常工作,例如:
public void fixGridAlarm(DataGridView gvw)
{
// ...
for (int i = 0; i < gvw.Columns.Count; i++)
gvw.Columns[i].DataPropertyName = gvw.Columns[i].Name;
BindAlarmlarGrid();
}
答案 1 :(得分:0)
我通过改变我的绑定方法而不是使用DataTable
public void BindAlarmlarGrid()
{
string CSVFilePathName = pathAlarms;
string[] Lines = File.ReadAllLines(CSVFilePathName);
string[] Fields;
for (int i = 0; i < Lines.GetLength(0); i++)
{
Fields = Lines[i].Split(new char[] { ',' });
dgvAlarmlar.Rows.Add(Fields);
}
}