2017-07-06 192 views
0

我需要使用列表中的項目填充DataGridView。將項目添加到DataGridView從列表框到單列

我需要GridView的第一行填充字符串列表中的項目,我需要對GridView中的項目逐個進行一些處理,並將結果添加到第二行(字符串)。

目前即時通訊綁定的DataGridView這樣

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

我需要預定義的列名第一行中添加字符串,處理這些字符串逐個更新第二column..what是最好的方法去做這個?

回答

1

這裏是您的解決方案,

 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"); 

希望這將幫助您爲您的解決方案。

1

首先,您需要以編程方式構建您的列,或者您可以使用設計器 - 這取決於您。爲了展示整個示例,我將對其全部編碼:

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; 
     } 
    } 
}