从文本文件中放入数据并将ComboBox放在DataGridView中

时间:2014-03-09 12:46:59

标签: c# datagridview datagridviewcombobox datagridviewcomboboxcell

我尝试从文本文件中获取数据。接下来我想要一个列作为comboBox。我不知道该怎么做。我应该按相反的顺序做吗?如何将ColumnComboBox放在现有的DataGridView中?

创建列ComboBox的代码:

private void FillUslugaComboBoxDataGridView()
    {
        try
        {
            StreamReader sr = new StreamReader(@"C:\Users\Radek\Documents\Visual Studio 2010\Projects\Salon Fryzjerski\Salon Fryzjerski\Salon Fryzjerski\Baza\Uslugi.txt");
            string line = sr.ReadLine();
            DataGridViewComboBoxColumn usluga = new DataGridViewComboBoxColumn();
            if (line != null)
            {
                while (line != null)
                {
                    usluga.Items.Add(line);
                    line = sr.ReadLine();

                }
            }
            else
            {

                usluga.Items.Add("Error to fill, column is null");
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

1 个答案:

答案 0 :(得分:0)

您必须将该列添加到datagridview。例如,请参阅下面的示例代码:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace SOWinForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private DataGridView DataGridView1;
        private void Form1_Load(object sender, EventArgs e)
        {
            DataGridView1 = new DataGridView();
            var column = CreateComboBoxColumn();
            SetAlternateChoicesUsingDataSource(column);
            DataGridView1.Columns.Add(column);
            Controls.Add(DataGridView1); 
        }

        private DataGridViewComboBoxColumn CreateComboBoxColumn()
        {
            DataGridViewComboBoxColumn column =
                new DataGridViewComboBoxColumn();
            {
                column.DataPropertyName = "Name";
                column.HeaderText = "Name";
                column.DropDownWidth = 150;
                column.Width = 100;
                column.MaxDropDownItems = 3;
                column.FlatStyle = FlatStyle.Flat;
            }
            return column;
        }

        private void SetAlternateChoicesUsingDataSource(DataGridViewComboBoxColumn comboboxColumn)
        {
            {
                comboboxColumn.DataSource = RetrieveNames();
                comboboxColumn.ValueMember = "Name";
                comboboxColumn.DisplayMember = comboboxColumn.ValueMember;
            }
        }

        private List<Student> RetrieveNames()
        {
            return new List<Student>() { new Student() { Name = "Rohan" }, new Student() { Name = "Ram" } };
        }

    }

    public class Student
    {
        public string Name { get; set; }
    }
}