【问题标题】:Why an auto incremented column in datatable is coming empty?为什么数据表中的自动递增列变为空?
【发布时间】:2018-04-06 10:57:33
【问题描述】:

我在数据表中创建了一个身份列 id,其自动递增等于 true,但它是空的。

为什么?

        Datatable dt= new datatable();

        DataColumn dc = new DataColumn("id", typeof(int));

        dc.AutoIncrement = true;
        dc.AutoIncrementSeed = 1;
        dc.AutoIncrementStep = 1;
        dt.Columns.Add(dc);

        dc = new DataColumn("NITNo", typeof(string));
        dc.DefaultValue = txtNitNo.Text.ToString();
        dt.Columns.Add(dc);

        dc = new DataColumn("WorkNo", typeof(string));
        dc.DefaultValue = txtWorkNo.Text.ToString();
        dt.Columns.Add(dc);
        //dt.Rows.rem

        //Bind Data to GridView
        gvBOQ.Caption = Path.GetFileName(FilePath);
        gvBOQ.DataSource = dt;
        gvBOQ.DataBind();

【问题讨论】:

    标签: c# asp.net c#-4.0 datatable webforms


    【解决方案1】:

    如果向DataTable添加数据,则必须确保Identity Column中的值为null

    //create a datatable
    DataTable table = new DataTable();
    
    //auto increment column
    DataColumn column = new DataColumn("id", typeof(int));
    column.AutoIncrement = true;
    column.AutoIncrementSeed = 1;
    column.AutoIncrementStep = 1;
    table.Columns.Add(column);
    
    //add a normal column
    column = new DataColumn("value", typeof(string));
    table.Columns.Add(column);
    
    //add some data to the table
    table.Rows.Add(null, "Netherlands");
    table.Rows.Add(null, "Japan");
    table.Rows.Add(99, "Australia");
    table.Rows.Add(null, "America");
    

    生成的表格将如下所示

    id  value
    1   Netherlands
    2   Japan
    99  Australia
    100 America
    

    【讨论】:

    • 你好,谢谢,抱歉,我不能插入假数据,因为它会干扰原始数据并可能导致客户端出现问题。
    • 假数据仅供演示。重要的是在填充数据表时 id 列是空的。
    • 你能修改我的代码吗,因为我对它完全陌生。
    • 修改不多。您只需将数据添加到数据表并将其绑定到 GridView。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 2015-12-02
    • 2021-10-07
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 2016-10-01
    相关资源
    最近更新 更多