DataTable的自定义数据 [英] Custom data for DataTable

查看:117
本文介绍了DataTable的自定义数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用自定义数据创建DataTable。两个字段的自定义数据组合:

I create DataTable with Custom Data. Custom Data composite of two fields:

 class DataItem
    {
        //properties
       public string value { get; set; }//will connect to datagridview
       public bool IsReserved { get; }//additional data

        public DataItem()
        {
            this.value = string.Empty;
            this.IsReserved = false;
        }
        //ctor
        public DataItem(string value, bool IsReadOnly)
        {
            this.value = value;
            this.IsReserved = IsReadOnly;
        }
        //Convert to string
        public override string ToString() { return this.value; }

我将DataTable与自定义数据连接到DataGridView,并覆盖了一些函数。

I connect DataTable with custom data to DataGridView, and overridden some functions.

DataGridView正确显示我的自定义数据。但是当我编辑DataGridView的任何单元格并按Enter键时。

DataGridView show my custom data correctly. But when I do edit the any cell of DataGridView and press Enter.

我有一个错误:

我无法理解:什么添加到代码或什么覆盖?

I can't understand: what add to code or what override?

这是我的简单示例:

SampleCode

SampleCode




推荐答案

嗨迈克,

那是因为你定义了使用dtSpeciaEditor.cs中的以下代码将 DataItem
的DataTable列的类型:

That is because you define the type of the DataTable column to DataItem with the following code in dtSpeciaEditor.cs:

            column = new DataColumn("Balloned", typeof(DataItem));
            column.DefaultValue = new DataItem();
            column.AllowDBNull = false;

            // Add the Column to the DataColumnCollection.
            this.Columns.Add(column);

            column = new DataColumn("FileType", typeof(DataItem));
            column.DefaultValue = new DataItem();

            // Add the Column to the DataColumnCollection.
            this.Columns.Add(column);

然后将此数据表绑定到datagridview,因此datagridview的类型也是DataItem。但是,当您向datagridview单元格输入值时,默认情况下它是字符串类型,因此您无法将字符串转换为DataItem。

Then you bind this datatable to the datagridview, so the type of datagridview is also DataItem. However, when you input a value to the datagridview cell, it is string type by default, so you can not convert string to DataItem.

如果要为datagridview输入值,有两种解决方案如下:

If you want to input a value for the datagridview, there are two solutions as below:

1,将列的类型更改为"string"。

1, Change the type of the column to "string".

2,输入DataItem类型data:

2, Input a DataItem type of data:

        private void button1_Click(object sender, EventArgs e)
        {
            DataItem data;
            data = new DataItem(textBox1.Text, true);

            int rowIndex = Convert.ToInt32(textBox2.Text);
            int columnIndex = Convert.ToInt32(textBox3.Text);

            dgv.Rows[rowIndex].Cells[columnIndex].Value = data;
        }

希望这会有所帮助!

最好的问候,

Stanly


这篇关于DataTable的自定义数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆