Add multiple DataColumns to a DataTable using ASP.NET
Output:
ASP.NET Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
<%@ 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 dc = new DataColumn(); dc.ColumnName = "BookID"; dc.DataType = typeof(int); //this line add single DataColumn to DataTable dt.Columns.Add(dc); DataColumn dc2 = new DataColumn(); dc2.ColumnName = "BookName"; dc2.DataType = typeof(string); DataColumn dc3 = new DataColumn(); dc3.ColumnName = "BookPrice"; dc3.DataType = typeof(decimal); //this line add two DataColumn to DataTable at a time dt.Columns.AddRange(new DataColumn[] {dc2,dc3}); dt.Rows.Add(new object[] { 1,"asp.net ebook",4 }); dt.Rows.Add(new object[] { 2, "ajax ebook",5.05 }); GridView1.DataSource = dt; GridView1.DataBind(); } </script> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title> CODE4EXAMPLE.COM </title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <form id="form1" runat="server"> <h2 style="color:DarkBlue; font-style:italic;"> Using AddRange() method - How to add multiple <br /> DataColumn to a DataTable programmatically in ado.net </h2> <hr align="left" color="CornFlowerBlue" /> <asp:GridView ID="GridView1" runat="server" CssClass="table table-striped table-dark" > </asp:GridView> <br /> <asp:Button ID="Button2" runat="server" OnClick="Button1_Click" Text="Populate GridView" CssClass="btn btn-primary btn-lg" /> </form> </div> </body> </html> |