GridView Nesnesinde Sütunların Sırasını Değiştirmek
Merhaba arkadaşlar bu makalemizde DataTable SetOrdinal özelliğini kullanarak GridView nesnesinde sütunların yerini değiştirebileceğiz. Bu örneğimizde dt.Columns[1].SetOrdinal(2);
ile 1. sütunu 2. sütun ile yerini değiştiriyoruz.
Şekil 1
Şekil 2
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
SqlConnection con;
string constr;
string sql;
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
DataTable dt;
protected void BindData()
{
{
constr = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\kategori.mdf;Integrated Security=True";
sql = "select * from [dbo].[Table]";
con = new SqlConnection(constr);
con.Open();
cmd = new SqlCommand(sql, con);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
con.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
constr = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\kategori.mdf;Integrated Security=True";
sql = "select * from [dbo].[Table]";
con = new SqlConnection(constr);
cmd = new SqlCommand(sql, con);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
con.Open();
da.Fill(ds);
dt = ds.Tables["Table"];
con.Close();
//gview daki 1.sutunu 2.sutun ile yerini degistiriyoruz.
dt.Columns[1].SetOrdinal(2);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4" Font-Names="Tahoma" Font-Size="Large" GridLines="Horizontal">
<FooterStyle BackColor="White" ForeColor="#333333" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#333333" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#487575" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#275353" />
</asp:GridView>
<br />
<asp:Button ID="Button1" runat="server" Font-Names="Tahoma" Font-Size="Large" Height="45px" OnClick="Button1_Click" Text="Degistir" Width="174px" />
</div>
</form>
</body>
</html>
Bir makalenin daha sonuna geldik. Bir sonraki makalede görüşmek üzere. Bahadır ŞAHİN