在C#DataGridView中添加Combobox(Winforms)

时间:2015-04-14 06:54:57

标签: c# winforms csv datagridview combobox

我的表单中有很少的DataGrids,我的数据源是CSV文件,我已在其中设置要显示的列。简而言之,当我选择New Project时,CSV文件从默认位置加载并显示一个空行和列名称的网格。 现在我要做的是为第1列添加一个下拉列表(组合框)控件,如果是空网格,则保持为空,如果是带有数据的CSV文件,则动态显示数据,但我无能为力它。我从未在网格中添加组合框。包含MSDN的所有示例都令人困惑。 我是新手,明确的答案非常受欢迎。 这是代码,我如何加载CSV数据

string[] strColumns = null;
string[] strData = null;

StreamReader sr = new StreamReader(strCSV);
DataTable dt = null;
int RowCount = 0;

while (!sr.EndOfStream)
{
    String strRow = sr.ReadLine().Trim();
    if (strRow.Length > 0)
    {
        strData = strRow.Split(delimter);

        if (RowCount == 0)
        {
            RowCount = 1;
            strColumns = strRow.Split(delimter);
            dt = new DataTable();

            foreach (string csvcolumn in strColumns)
            {
                DataColumn column = new DataColumn(csvcolumn.ToUpper(), typeof(string));
                column.DefaultValue = string.Empty;
                dt.Columns.Add(column);
            }
        }

        else
        {
            DataRow row = dt.NewRow();
            for (int i = 0; i < strColumns.Length; i++)
            {
                row[strColumns[i]] = strData[i] == null ? string.Empty : strData[i].ToString();
            }
            dt.Rows.Add(row);
        }
    }
}
sr.Close();
sr.Dispose();
return dt;

2 个答案:

答案 0 :(得分:0)

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        dataGridView1.ColumnCount = 3;
        dataGridView1.Columns[0].Name = "Product ID";
        dataGridView1.Columns[1].Name = "Product Name";
        dataGridView1.Columns[2].Name = "Product Price";

        string[] row = new string[] { "1", "Product 1", "1000" };
        dataGridView1.Rows.Add(row);
        row = new string[] { "2", "Product 2", "2000" };
        dataGridView1.Rows.Add(row);
        row = new string[] { "3", "Product 3", "3000" };
        dataGridView1.Rows.Add(row);
        row = new string[] { "4", "Product 4", "4000" };
        dataGridView1.Rows.Add(row);

        DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
        cmb.HeaderText = "Select Data";
        cmb.Name = "cmb";
        cmb.MaxDropDownItems = 4;
        cmb.Items.Add("True");
        cmb.Items.Add("False");
        dataGridView1.Columns.Add(cmb);

    }
}

答案 1 :(得分:0)

             DataGridViewComboBoxCell comboJob = new DataGridViewComboBoxCell();

            //these data will be displayed in comboBox:

            string[] data = JobIdList.ToArray();

            comboJob.Items.AddRange(data);

            this.dgInfo()[e.ColumnIndex, e.RowIndex] = comboJob;

            bValidating = true;