将项从列表框添加到数据网格视图到单个列



我需要用列表中的项目填充 DataGridView。

我需要用字符串列表中的项目填充的 GridView 的第一行,我需要对 GridView 中的项目进行一些处理,并将结果添加到第二行(字符串(。

目前我像这样绑定数据网格视图

dataGridView1.DataSource = mylist.ConvertAll(x => new { Value = x });
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

我需要预定义列名在第一行添加字符串,逐个处理这些字符串并更新第二列。最好的方法是什么?

这是您的解决方案,

dgvDataViewer.ColumnCount = 1;
dgvDataViewer.Columns[0].Name = "Language";
string[] row = new string[] { "C#" };
dgvDataViewer.Rows.Add(row);
row = new string[] { "C++" };
dgvDataViewer.Rows.Add(row);
row = new string[] { "C" };
dgvDataViewer.Rows.Add(row);
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.HeaderText = "HeaderText";
cmb.Name = "Name";
cmb.FlatStyle = FlatStyle.System;
dgvDataViewer.Columns.Add(cmb);
DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell)dgvDataViewer.Rows[0].Cells[1];
dgvcbc.Items.Add("Apple");
dgvcbc.Items.Add("Google");
dgvcbc.Items.Add("Apache");
dgvcbc.Items.Add("Microsoft");

希望这对您的解决方案有所帮助。

首先,您需要以编程方式构建列,或者可以使用设计器 - 这取决于您。 为了展示整个示例,我将对所有内容进行编码:

private DataGridView dgNew;
public MyForm()
{
InitializeComponent();
MyInitializeComponent();
}
private void MyInitializeComponent()
{
dgNew = new DataGridView();
var txtCol = new DataGridViewTextBoxColumn
{
HeaderText = "Column1",
Name = "Column1",
DataPropertyName = "Value"
};
dgNew.Columns.Add(txtCol);
txtCol = new DataGridViewTextBoxColumn
{
HeaderText = "Column2",
Name = "Column2",
};
dgNew.Columns.Add(txtCol);
var listOfStrings = new List<string> {"one", "two", "three"};
dgNew.DataSource = listOfStrings.ConvertAll(x => new { Value = x }); ;
dgNew.Location = dg.Location;
dgNew.Parent = this;
this.Load += Form_Load;
}
private void Form_Load(object sender, EventArgs e)
{
// Iterate over the rows, ignoring the header row
foreach (var row in dgNew.Rows.OfType<DataGridViewRow>().Where(a => a.Index != -1))
{
var col1Value = row.Cells["Column1"].Value?.ToString();
var col2Cell = row.Cells["Column2"];
if (col1Value == null) continue;
switch (col1Value)
{
case ("one"):
col2Cell.Value = "row1, col2 val";
break;
case ("two"):
col2Cell.Value = "row2, col2 val";
break;
case ("three"):
col2Cell.Value = "row1, col3 val";
break;
}
}
}

最新更新