将dataGridView列转换为checkbox列

时间:2013-05-28 16:23:27

标签: c# checkbox datagridview

我正在制作一个程序来检查我在大学里留下的课程数量。 我将信息从csv加载到数据集中,然后用数据网格显示。

我想要一些列(实验室和理论)有复选框单元格,以便我可以检查我通过的课程,然后将它们保存回csv以便稍后再次加载它们(当我通过somethnig:P时) 。 但是我将这些(字符串)列转换为复选框时遇到问题,因为我在c#

中没那么有经验

这是我的代码:

string delimiter = ";";
string tablename = "paTable";
filename = "aname";
DataSet dataset = new DataSet();
StreamReader sr = new StreamReader(filename);
DataGridViewColumn column = new DataGridViewColumn();
dataset.Tables.Add(tablename);

dataset.Tables[tablename].Columns.Add("A/A");
dataset.Tables[tablename].Columns.Add("Course");
dataset.Tables[tablename].Columns.Add("Semester");
dataset.Tables[tablename].Columns.Add("Theory");
dataset.Tables[tablename].Columns.Add("Lab");
dataset.Tables[tablename].Columns.Add("Passed");

string alldata = sr.ReadLine();
while (sr.Peek() != -1)
{
alldata = sr.ReadLine();
string[] rows;
rows = alldata.Split("\r".ToCharArray());

foreach (string r in rows)
{
string[] items = r.Split(delimiter.ToCharArray());
dataset.Tables[tablename].Rows.Add(items);
}

this.dataGridView1.DataSource = dataset.Tables[0].DefaultView;
}

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:1)

您可以将文本框“转换”为如下所示的复选框:

        dgv.Columns.RemoveAt(<NumberColumn2Remove>);

        DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn;
        chk.HeaderText = "<HeaderText>";
        chk.Name = "<WhatEver>";
        chk.DataPropertyName = "<DataField2Bind2>";

        dgv.Columns.Insert(<NumberColumn2Insert>, chk);

答案 1 :(得分:0)

您需要一个DataGridViewCheckBoxColumn:

所以你需要更换

DataGridViewColumn column = new DataGridViewColumn();

使用DataGridViewCheckBoxColumn。请阅读以下内容:

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcheckboxcolumn.aspx

答案 2 :(得分:0)

如果您手动创建列并将其添加到DataGridView,我认为您可以按原样保留DataSet - 加载流程。

关闭AutoGenerateColumns并手动添加:

dataGridView1.AutoGenerateColumns = false;
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn { Name="Course", ... } );
dataGridView1.Columns.Add(new DataGridViewCheckBoxColumn { Name="Passed", ... } );
...

网格视图应在您与DataView绑定之后填充:

dataGridView1.DataSource = dataset.Tables[0].DefaultView;

修改

因为它依赖于强类型和适当的绑定,所以可能更好的选择是创建一个表示CSV记录的类(假定的类型)。如果此类实现INotifyPropertyChanged接口,则可以在DataGridView中编辑值,并以最小的努力反映在类中。

public class CsvDataRow : INotifyPropertyChanged
{
    private bool _aa;
    private string _course;
    private int _semester;
    private double _theory;
    private double _lab;
    private bool _passed;

    public bool AA { get { return _aa; } set { if (value == _aa) return; _aa = value; NotifyPropertyChanged("AA"); } }
    public string Course { get { return _course; } set { if (value == _course) return; _course = value; NotifyPropertyChanged("Course"); } }
    public int Semester { get { return _semester; } set { if (value == _semester) return; _semester = value; NotifyPropertyChanged("Semester"); } }
    public double Theory { get { return _theory; } set { if (value == _theory) return; _theory = value; NotifyPropertyChanged("Theory"); } }
    public double Lab { get { return _lab; } set { if (value == _lab) return; _lab = value; NotifyPropertyChanged("Lab"); } }
    public bool Passed { get { return _passed; } set { if (value == _passed) return; _passed = value; NotifyPropertyChanged("Passed"); } }

    char _delimiter;

    // static factory method creates object from CSV row
    public static CsvDataRow Create(string row, char delimiter)
    {
        return new CsvDataRow(row, delimiter);
    }

    // private constructor initializes property values
    private CsvDataRow(string row, char delimiter)
    {
        _delimiter = delimiter;

        var values = row.Split(_delimiter);
        AA = (values[0].ToString().Equals("1"));
        Course = Convert.ToString(values[1]);
        Semester = Convert.ToInt32(values[2]);
        Theory = Convert.ToDouble(values[3]);
        Lab = Convert.ToDouble(values[4]);
        Passed = (values[5].ToString().Equals("1"));
    }

    // a method to convert back into a CSV row
    public string ToCsvString()
    {
        var values = new string[] { (AA ? 1 : 0).ToString(), Course, Semester.ToString(), Theory.ToString(), Lab.ToString(), (Passed ? 1: 0).ToString() };
        return string.Join(_delimiter.ToString(), values);
    }

    // INotifyPropertyChanged interface requires this event
    public event PropertyChangedEventHandler PropertyChanged;

    // helper method to raise PropertyChanged event
    private void NotifyPropertyChanged(string name)
    {
        if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}

CSV文件本身可以用类表示:

public class CsvDataSource
{
    public char Delimiter { get; private set; }
    public CsvDataSource()
        : this(',')
    { }

    public string[] Columns { get; private set; }

    public ObservableCollection<CsvDataRow> Rows { get; private set; }

    public CsvDataSource(char delimiter)
    {
        Delimiter = delimiter;
    }

    public void LoadCsv(string csvFileName)
    {
        string header;
        string data;

        using (var reader = new StreamReader(csvFileName))
        {
            header = reader.ReadLine(); // assumes 1st row is column headers
            data = reader.ReadToEnd();
        }

        Columns = header.Split(Delimiter);
        var rows = Regex.Split(data, Environment.NewLine);

        if (!rows.Select(row => row.Split(Delimiter)).All(row => row.Length == Columns.Length)) throw new FormatException("Inconsistent data format.");
        Rows = new ObservableCollection<CsvDataRow>(rows.Select(row => CsvDataRow.Create(row, Delimiter)));
    }
}

然后可以将DataGridView绑定到Rows实例的CsvDataSource属性,因此表单的代码可能如下所示:

public partial class Form1 : Form
{
    private CsvDataSource _data;
    private ObservableCollection<CsvDataRow> _rows;

    public Form1()
    {
        InitializeComponent();
    }

    public void LoadCsv(CsvDataSource data)
    {
        _data = data;
        _rows = _data.Rows;
        dataGridView1.DataSource = _rows;
    }

    public void SaveCsv(string path)
    {
        using (var writer = new StreamWriter(path))
        {
            writer.WriteLine(string.Join(_data.Delimiter.ToString(), _data.Columns));
            foreach (var row in _rows)
            {
                writer.WriteLine(row.ToCsvString());
            }
        }
    }
}

当然你有一个调用SaveCsv方法的按钮,你需要另一个按钮来向/从你的DataGridView添加/删除行。您还需要在try / cath块中包装文件I / O操作。

这是一个快速总结的实现,需要一些额外的工作才能完全正常运行,但它提供了一个想法,并且开箱即用。

这样,CsvDataRow类完全处理了“定义列”部分,为每条记录提供了强类型。没有DataSet,没有DataColumn,也没有DataGridViewColumn。只是数据和一些数据绑定。