Add a DataRow to DataTable
AddDataRowToDataTable.aspx
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html>
<script runat="server">
void Button1_Click(object sender, System.EventArgs e)
{
DataTable dt = new DataTable();
dt.TableName = "Books";
DataColumn dc1 = new DataColumn();
dc1.ColumnName = "BookID";
dc1.DataType = typeof(int);
dc1.AllowDBNull = false;
DataColumn dc2 = new DataColumn();
dc2.ColumnName = "BookName";
dc2.DataType = typeof(string);
DataColumn dc3 = new DataColumn();
dc3.ColumnName = "Author";
dc3.DataType = typeof(string);
dt.Columns.AddRange(new DataColumn[] { dc1,dc2,dc3 });
dt.Rows.Add(new object[] { 1, "Learning ActionScript 3.0, Second Edition", "Rich Shupe" });
dt.Rows.Add(new object[] { 2, "Flash CS5: The Missing Manual", "Chris Grover" });
GridView1.DataSource = dt;
GridView1.DataBind();
//add another one DataRow in DataTable
DataRow dr = dt.NewRow();
dr["BookID"] = 3;
dr["BookName"] = "Google SketchUp: The Missing Manual";
dr["Author"] = "Chris Grover";
dt.Rows.Add(dr);
Label1.Text = "add another one DataRow into DataTable";
GridView2.DataSource = dt;
GridView2.DataBind();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to add DataRow to DataTable in ado.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:DarkBlue; font-style:italic;">
How to add DataRow to DataTable in ado.net
</h2>
<hr width="500" align="left" color="CornFlowerBlue" />
<asp:GridView
ID="GridView1"
runat="server"
BorderColor="Snow"
ForeColor="Snow"
Width="550"
>
<HeaderStyle BackColor="Crimson" Height="35" />
<RowStyle BackColor="DodgerBlue" />
<AlternatingRowStyle BackColor="SkyBlue" />
</asp:GridView>
<br />
<asp:Label
ID="Label1"
runat="server"
Font-Size="Medium"
ForeColor="HotPink"
>
</asp:Label>
<br /><br />
<asp:GridView
ID="GridView2"
runat="server"
BorderColor="Snow"
ForeColor="Snow"
Width="550"
>
<HeaderStyle BackColor="Crimson" Height="35" />
<RowStyle BackColor="DodgerBlue" />
<AlternatingRowStyle BackColor="SkyBlue" />
</asp:GridView>
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Populate GridView"
Height="45"
Font-Bold="true"
ForeColor="DarkBlue"
/>
</div>
</form>
</body>
</html>
- How to get maximum size of a column in a DataTable
- How to change DataTable columns order
- How to insert a new row into DataTable
- How to use DataTable AcceptChanges() method
- How to use DataTable RowDeleting event
- How to merge two DataTables
- How to create a DataView
- How to filter data in a DataView
- How to get the source table of a DataView
- How to sort a DataView