Get whether DataTable contains a specified DataColumn. Verify if a column exist in a DataTable
Example 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
<%@ 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); 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[] {dc,dc2,dc3}); dt.Rows.Add(new object[] { "1", "Network Your Computers & Devices Step by Step", "Ciprian Adrian Rusen" }); dt.Rows.Add(new object[] { "2", "Microsoft® Expression® Web 4 Step by Step", "Chris Leeds" }); dt.Rows.Add(new object[] { "3", "My New iPad, Second Edition", "Wallace Wang" }); GridView1.DataSource = dt; GridView1.DataBind(); //this line check the 'BookName' DataColumn exists in DataTable or not Boolean columnExists = dt.Columns.Contains("BookName"); Label1.Text = "'BookName' DataColumn exists in DataTable? = " + columnExists; } </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"> <div> <h2> Using Contains() method - How to check the DataTable <br /> contains a DataColumn with the specified name in ado.net </h2> <hr color="CornFlowerBlue" /> <asp:Label ID="Label1" runat="server" Font-Size="Large" CssClass="alert alert-primary mb-1 d-block" > </asp:Label> <asp:GridView ID="GridView1" runat="server" CssClass="table table-striped" > </asp:GridView> <br /> <asp:GridView ID="GridView2" runat="server" CssClass="table table-striped table-dark" > </asp:GridView> <br /> <asp:GridView ID="GridView3" runat="server" CssClass="table table-striped table-dark" > </asp:GridView> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Populate GridView" CssClass="btn btn-primary btn-lg" /> </div> </form> </div> </body> </html> |