Add (Insert) new Column with default Value to existing DataTable in C# and VB.Net

Last Reply 3 months ago By pandeyism

Posted 3 months ago

How to add value to datarow as Occasion. I have added new coulm as like this 

dt.Columns.Add("Occasion");

So the column will be created but rows will be empty. I need to fill some data how to add data in this.

like want to add default value as one,two etc.

You are viewing reply posted by: pandeyism 3 months ago.
Posted 3 months ago Modified on 3 months ago

Hi SUJAYS,

Refer below code.

HTML

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
</asp:GridView>

Namespaces

C#

using System.Data;

VB.Net

Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                        new DataColumn("Name", typeof(string)),
                        new DataColumn("Country",typeof(string)) });
        dt.Rows.Add(1, "John Hammond", "United States");
        dt.Rows.Add(2, "Mudassar Khan", "India");
        dt.Rows.Add(3, "Suzanne Mathews", "France");
        dt.Rows.Add(4, "Robert Schidner", "Russia");
        DataColumn dataColumn = new DataColumn("Occasion", typeof(string));
        dataColumn.DefaultValue = "Test";
        dt.Columns.Add(dataColumn);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As DataTable = New DataTable()
        dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Country", GetType(String))})
        dt.Rows.Add(1, "John Hammond", "United States")
        dt.Rows.Add(2, "Mudassar Khan", "India")
        dt.Rows.Add(3, "Suzanne Mathews", "France")
        dt.Rows.Add(4, "Robert Schidner", "Russia")
        Dim dataColumn As DataColumn = New DataColumn("Occasion", GetType(String))
        dataColumn.DefaultValue = "Test"
        dt.Columns.Add(dataColumn)
        GridView1.DataSource = dt
        GridView1.DataBind()
    End If
End Sub

Screenshot