How to change the order of columns in a GridView using Asp.Net C #
I have a grid that is anchored by code where I also want to display the template field.
I am generating 3 columns in a DataTable to represent the grid, and the template field is a TextBox control.
My code for data binding ...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class gr4 : System.Web.UI.Page
{
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
cn = new SqlConnection("Data Source=AMIR-PC\\MOHEMMAD;Initial Catalog=CRM_InvestPlus;Integrated Security=True");
string query = "Select Capacity from Dealer_License_Capacity where ID='D00001' and Software_ID='001' and Version_ID='1'";
cn.Open();
cmd = new SqlCommand(query,cn);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
cn.Close();
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Software_Name", typeof(string));
dt.Columns.Add("Version_Name", typeof(string));
int count = Convert.ToInt32(ds.Tables[0].Rows[0][0].ToString());
for (int i = 0; i < count; i++)
{
DataRow dr = dt.NewRow();
dr["Name"] = "aaa";
dr["Software_Name"] = "bbb";
dr["Version_Name"] = "ccc";
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
My original code for the grid view:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
Grid display template field as first column, but I want to display template field as last column in output. Can I add more template fields to this grid.
Please, help..
Thank you in advance
+3
source to share
2 answers
You can use related fields as below
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" > /*changed to false*/
<Columns>
<asp:BoundField HeaderText="Name"
DataField="Name"/>
<asp:BoundField HeaderText="SoftwareName"
DataField="Software_Name"/>
<asp:BoundField HeaderText="VersionName"
DataField="Version_Name"/>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can change the order as you like.
+2
source to share