Get index of a DataColumn from a DataTable
IndexOfMethodDataTable.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 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", "Native Video in HTML5", "David Griffiths" });
dt.Rows.Add(new object[] { "2", "Best iPhone Apps, Second Edition", "J.D. Biersdorfer" });
dt.Rows.Add(new object[] { "3", "Microsoft® Silverlight® 4 Step by Step", "Laurence Moroney" });
dt.Rows.Add(new object[] { "4", "Premiere Elements 8: The Missing Manual", "Chris Grover" });
GridView1.DataSource = dt;
GridView1.DataBind();
//this line get the 'Author' DataColumn index in DataTable
int columnIndex = dt.Columns.IndexOf("Author");
Label1.Text = "'Author' DataColumn index in DataTable? = " + columnIndex;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to get the index of the DataColumn with the specific name from DataTable in ado.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:DarkBlue; font-style:italic;">
Using IndexOf() method - How to get the index of the
<br /> DataColumn with the specific name from DataTable in ado.net
</h2>
<hr width="550" align="left" color="CornFlowerBlue" />
<asp:GridView
ID="GridView1"
runat="server"
BorderColor="Snow"
ForeColor="Snow"
Width="525"
HeaderStyle-BackColor="DarkOrchid"
RowStyle-BackColor="SlateBlue"
AlternatingRowStyle-BackColor="MediumSlateBlue"
>
</asp:GridView>
<br /><br />
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="IndianRed"
>
</asp:Label>
<br /><br />
<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 count columns in a DataTable
- How to get column names from a DataTable
- How to get a DataTable columns data type
- How to convert a DataTable to an array of rows
- How to select data from a DataTable with condition
- How to set all the values for a DataRow through an array
- How to update a row in a DataTable
- How to create multi-column primary key for a DataTable
- How to use DataTable AcceptChanges() method
- How to use DataTable RowDeleting event