GridView cannot be delete value asp.net - c#

protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
string strQuery = "select Id, ItemName, FoundAt, TimeIn, ImageName from LostFound order by ID";
SqlCommand cmd = new SqlCommand(strQuery);
SqlConnection con = new SqlConnection(VisitorManagementConnectionString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
ViewState["dt"] = dt;
BindGrid();
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
dt.Dispose();
}
}
protected void BindGrid()
{
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void BtnLose_Click(object sender, EventArgs e)
{
Response.Redirect("SecurityLost.aspx");
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string ID = e.Row.Cells[0].Text;
foreach (Button button in e.Row.Cells[5].Controls.OfType<Button>())
{
if (button.CommandName == "Delete")
{
button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + ID + "?')){ return false; };";
}
}
}
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int ID = Convert.ToInt32(e.RowIndex);
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[ID].Delete();
string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(VisitorManagementConnectionString))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM LostFound WHERE ID = #ID"))
{
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
BindGrid();
}
when i press delete button the row can be delete but when i reload the
page the row i deleted still appeal back and my database also never be
deleted.
Can someone guide me where am I going wrong?
<asp:GridView ID="GridView1" runat="server" OnRowDataBound = "OnRowDataBound" AutoGenerateColumns = "false" OnRowDeleting="OnRowDeleting" Font-Names = "Arial" Caption = "Lose & Found" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField = "ID" HeaderText = "ID" />
<asp:BoundField DataField = "ItemName" HeaderText = "Item Name" />
<asp:BoundField DataField = "FoundAt" HeaderText = "Place" />
<asp:BoundField DataField = "TimeIn" HeaderText = "Time Found" />
<asp:ImageField DataImageUrlField = "ID" DataImageUrlFormatString = "Image.aspx?ImageID={0}" ControlStyle-Width = "100" ControlStyle-Height = "100" HeaderText = "Preview Image"/>
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
This my HTML file.

So from the comments we've established that the problem is that your ID is always 0.To make sure the ID comes through correctly you need to make two changes:
1.Change the Page_Load() event like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//Cut and paste the code to bind to the GridView here
}
}
2.Add this code to the RowDeleting event:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Int32.Parse(GridView1.Rows[e.RowIndex].Cells[0].Text);
}

Related

how do i get the fields selected in the gridview

So basically i want to create a booking and a booking can have multiple orders but i dont know how to store the orders that have been selected in the other pages etc. but I already know i have to do a cycle to run the gridview bue i dont know how to do that with a pager and with a search textbox.
this is how it looks:
Current CS
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Gestão_de_embarques
{
public partial class CriarEcomenda : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["constring"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
string user = Convert.ToString(Session["user"]);
username.Text = user;
if (Session["user"] == null || Session["login"] == null)
{
Response.Redirect("Login.aspx", false);
}
if (!Page.IsPostBack)
{
refreshdata();
}
con.Close();
}
public void refreshdata()
{
SqlCommand cmd = new SqlCommand("select DISTINCT No_ from [Encomenda]", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btnsearch_Click(object sender, EventArgs e)
{
con.Open();
if (txtSearch.Value == "")
{
refreshdata();
}
else
{
try
{
SqlCommand cmd = new SqlCommand("select DISTINCT No_ from [encomenda] where No_= #No_", con);
cmd.Parameters.Add("#No_", SqlDbType.NVarChar).Value = txtSearch.Value;
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
sdr.Close();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
else
{
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sdr.Close();
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
ButtonCreate.Visible = false;
}
}
catch(Exception ex)
{
}
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
refreshdata();
}
}
}
Well, if you were not data paging, then the un-bound check box would persist and survive even post backs.
But, since you have data paging? Then you persist the selected PK id from the database. (you don't have to display the pk row, but just set DataKeys = "ID" or what ever your PK row is from the database.
As noted, with searching and paging, you have to re-bind the grid, so you can't use the grid to persist the selected check boxes. Say we have a list of hotels to select.
Our markup would be this:
<div style="width:40%">
<asp:GridView ID="MyGrid" runat="server" CssClass="table table-hover"
DataKeyNames="ID" AutoGenerateColumns="false" OnRowDataBound="MyGrid_RowDataBound" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="HotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="HotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="Province" HeaderText="Province" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Show Selected rows" OnClick="Button1_Click" />
<br />
<br />
</div>
And code to load up this grid would be:
List<int> MySelected = new List<int>();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
LoadGrid();
ViewState["MySelected"] = MySelected;
}
else
{
MySelected = (List<int>)ViewState["MySelected"];
}
}
public void LoadGrid()
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from tblHotels ORDER BY HotelName",
new SqlConnection(Properties.Settings.Default.TEST3)))
{
cmdSQL.Connection.Open();
DataTable rst = new DataTable();
rst.Load(cmdSQL.ExecuteReader());
MyGrid.DataSource = rst;
MyGrid.DataBind();
}
}
protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int PkRow = (int)((DataRowView)e.Row.DataItem)["ID"];
CheckBox ckbox = (CheckBox)e.Row.FindControl("CheckBox1");
if (MySelected.Contains(PkRow)) {
ckbox.Checked = true;
}
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox ckBox = (CheckBox)sender;
GridViewRow gvRow = (GridViewRow)ckBox.Parent.Parent;
int RowPK = (int)(MyGrid.DataKeys[gvRow.RowIndex]["ID"]);
if (ckBox.Checked)
MySelected.Add(RowPK);
else
MySelected.Remove(RowPK);
}
Now how I just created a simple list. When you check a box, you simply add the PK row from the GridRow "PK" to the list.
The code to get/work the "list" from the database thus will look like this:
protected void Button1_Click(object sender, EventArgs e)
{
string MyPkList = string.Join(",", MySelected);
string strSQL = "SELECT * from tblHotels where ID IN(" + MyPkList + ")";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, new SqlConnection(Properties.Settings.Default.TEST3)))
{
cmdSQL.Connection.Open();
DataTable rstPickList = new DataTable();
rstPickList.Load(cmdSQL.ExecuteReader());
foreach (DataRow OneRow in rstPickList.Rows)
{
Response.Write("<h2> PK = " + OneRow["Id"].ToString() + " Hotel Name = " + OneRow["HotelName"] + "</h2>");
}
}
}
So, if I check say 3 rows, and hit that button, you get this:
this does mean that you have to set the check box to auto post back. And that thus means for a check box click, you do post-back. However, you could drop the whole grid in a update panel if you need to only post back that grid selecting part and not the whole page.
Once you have that list of PK values from the database, then as the button shows, we have to process against the database table, and we can't use the grid due to paging. As noted, if the gridview could fit on one page, then you would not need the persisting code, and you could just loop the grid view to get the checked rows - you would not need ANY code to persist the values.

asp.net dropdownlist first selection does not fire SelectedIndexChanged event

I've created a dropdownlist, and tried clicking on the first selection but there was no firing of the SelectedIndexChanged event. However, it worked perfectly fine for the rest of the options in the dropdownlist.
Here are my codes:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string member = (String)Session["ssmem"];
if (!IsPostBack)
{
if (Session["ssmem"] == null)
Response.Redirect("LoginforAccess.aspx");
else
{
Response.ClearHeaders();
Response.AddHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
Response.AddHeader("Pragma", "no-cache");
//if go back then must log in --2
}
//Dropdownlist
string strConnectionString =
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
//STEP1 : Define a connection to Database
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strcommand = "Select Username from [User] WHERE (UsergroupID = (SELECT UsergroupID FROM [User] AS User_1 WHERE (Username = #user)))";
SqlCommand cmd = new SqlCommand(strcommand, myConnect);
// cmd.Parameters.AddWithValue("#usergrp", groupid);
cmd.Parameters.AddWithValue("#user", member);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader();
DropDownList1.DataSource = reader;
DropDownList1.DataTextField = "Username";
DropDownList1.DataValueField = "Username";
DropDownList1.DataBind();
reader.Close();
myConnect.Close();
}
}
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
if (Session["ssmem"] != null)
MasterPageFile = "User.master";
//change the master page --1
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//chosen name to display stats
string choseuser = "";
choseuser = DropDownList1.SelectedItem.Text;
Response.Redirect("Substats.aspx?choseuser=" + choseuser);
}
}
Source view for dropdownlist:
<asp:DropDownList ID="DropDownList1" runat="server" Width="200px" Height="35px"
AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged"
ViewStateMode="Enabled">
</asp:DropDownList>
We have to add first item as title to the dropdownlist,
and instead of using datasource used dr.Read() in while loop for adding the items on dropdownlist.
This problem occurs because in dropdownlist first item is selected bydefault and it is not reflected on selection
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" ViewStateMode="Enabled">
<asp:ListItem>Select College</asp:ListItem>
<!--Add one item as title into dropdownlist in edit item of dropdownlist-->
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write("hello");
try
{
string sel = "select name from websites";
SqlCommand cmd = new SqlCommand(sel,con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
/* DropDownList1.DataSource = dr;
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "name";
DropDownList1.DataBind();*/
while (dr.Read())//used dr.read() instead of datasource
{
DropDownList1.Items.Add(dr["name"].ToString());
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand("select url from websites where name = #itm", con);
cmd.Parameters.AddWithValue("#itm", DropDownList1.SelectedItem.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
Response.Redirect(dr["url"].ToString());
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}

Deleting record from gridview in ASP.NET application

I have the below gridview on a page to display users with a role of "Reviewer". The grid pulls up the records correctly. On the gridview is a "delete" button to remove the Reviewer role. The stored procedure that is called is working correctly when ran manually, but I seem to be missing something on the aspx or codebehind page as while no error is returned, no record is deleted either.
aspx control for gridview:
<asp:GridView ID="GridView1" runat="server" Caption="Current Reviewers" AllowSorting="True" PagerSettings-Mode="NumericFirstLast" OnPageIndexChanging="GridView1_PageIndexChanging"
CaptionAlign="Top" EmptyDataText="No Reviewers Configured." PageSize="10" AllowPaging="true" PagerStyle-HorizontalAlign="Center" PagerStyle-Font-Size="Large"
AutoGenerateColumns="false" AlternatingRowStyle-BackColor="#cccccc" DataKeyNames="UserId" OnRowDeleting="DeleteRecord">
<Columns>
<asp:BoundField DataField="UserId" HeaderText="Id" ItemStyle-Width="300" />
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="250" />
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to Delete the record?')">
<asp:LinkButton ID="lnkB" runat="Server" Text="Delete" CommandArgument='<%# Eval("UserId") %>' CommandName="DeleteRecord"></asp:LinkButton>
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Updated with full code behind:
namespace cs1.Admin
{
public partial class ReviewerMaintenance : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList1();
}
}
private void BindDropDownList1()
{
string connectionString = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
string selectSQL = String.Format("SELECT Id as UserId, FirstName + ' ' + LastName As Name from AspNetUsers where Id in(SELECT UserId from AspNetUserRoles where RoleId = 1)");
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Reviewer");
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindDropDownList1(); //bindgridview will get the data source and bind it again
}
protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
{
string UserId = GridView1.DataKeys[e.RowIndex].Value.ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
SqlCommand dCmd = new SqlCommand();
{
conn.Open();
dCmd.CommandText = "Reviewer_Delete";
dCmd.CommandType = CommandType.StoredProcedure;
dCmd.Parameters.Add("#UserId", SqlDbType.NVarChar).Value = UserId;
dCmd.Connection = conn;
dCmd.ExecuteNonQuery();
// Refresh the data
BindDropDownList1();
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
}
}
Try to use the OnRowCommand event of the GridView to handle this.
In your Gridview markup:
ensure OnRowCommand="GridView1_RowCommand" is present.
In your code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{ /* Set a breakpoint here and make sure:
A.) You are hitting this method
B.) Get value of e.CommandName */
if (e.CommandName == "EditRecord")
{
// Run your edit/update logic here if needed
}
if (e.CommandName == "DeleteRecord")
{
// Delete the record here
string UserId = GridView1.DataKeys[e.RowIndex].Value.ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
SqlCommand dCmd = new SqlCommand();
{
conn.Open();
dCmd.CommandText = "Reviewer_Delete";
dCmd.CommandType = CommandType.StoredProcedure;
dCmd.Parameters.Add("#UserId", SqlDbType.NVarChar).Value = UserId;
dCmd.Connection = conn;
dCmd.ExecuteNonQuery();
// Refresh the data
BindDropDownList1();
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
This ended up being a very simple thing. On the aspx page I had both the OnRowDeleting and CommandName elements set to the same value of "DeleteRecord".
Changing the CommandName value to "Delete" allowed the code to be evaluated and the stored procedure to be called successfully.

GridView RowUpdating returns old values after PostBack

I got a problem with my GridView. When I try to edit my GridView, I only get the old values in return.
Here's the RowUpdating event:
protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
TextBox nVorname = (TextBox)row.FindControl("newVorname");
TextBox nNachname = (TextBox)row.FindControl("newNachname");
TextBox nTelnr = (TextBox)row.FindControl("newTelnr");
TextBox nEmail = (TextBox)row.FindControl("newEmail");
HiddenField tid = (HiddenField)row.FindControl("id");
grid.EditIndex = -1;
SqlConnection sqlConn = new SqlConnection("server=localhost;Integrated Security=true;database=Telefonbuch;");
sqlConn.Open();
SqlCommand cmd = new SqlCommand("update dasOertliche set vorname= #vorname, nachname=#nachname, telefonnr =#telnr, email =#email where id = #id", sqlConn);
cmd.Parameters.Add("#vorname", SqlDbType.VarChar);
cmd.Parameters["#vorname"].Value = nVorname;
cmd.Parameters.Add("#nachname", SqlDbType.VarChar);
cmd.Parameters["#nachname"].Value = nNachname.Text;
cmd.Parameters.Add("#email", SqlDbType.VarChar);
cmd.Parameters["#email"].Value = nEmail.Text;
cmd.Parameters.Add("#telnr", SqlDbType.VarChar);
cmd.Parameters["#telnr"].Value = nTelnr.Text;
cmd.Parameters.Add("#id", SqlDbType.Int);
cmd.Parameters["#id"].Value = tid.Value;
cmd.ExecuteNonQuery();
sqlConn.Close();
bind();
}
The TemplateField from the .aspx:
<Columns>
<asp:TemplateField HeaderText = "Vorname">
<ItemTemplate> <%#Eval ("vorname") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="newVorname" runat="server" Text='<%#Eval ("vorname") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</columns>
And my GridView code:
<asp:GridView runat="server" ID="grid" BorderWidth="0px" CellPadding="10"
CellSpacing="10" HorizontalAlign="Center" AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True" onrowcancelingedit="grid_RowCancelingEdit"
onrowediting="grid_RowEditing" onrowupdating="grid_RowUpdating"
AutoGenerateColumns="False">
Like I said, it always returns the old values. Any suggestions?
My Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
bind();
if (!Page.IsPostBack)
{
bind();
}
}
My bind():
public void bind()
{
SqlConnection sqlConn = new SqlConnection("server=localhost;Integrated Security=true;database=Telefonbuch;");
sqlConn.Open();
SqlDataAdapter sqlComm = new SqlDataAdapter("SELECT id, vorname AS 'Vorname', nachname AS 'Nachname', telefonnr, email AS 'E-Mail' FROM dasOertliche ORDER BY nachname ASC", sqlConn);
DataSet ds = new DataSet();
sqlComm.Fill(ds, "dasOertliche");
grid.DataSource = ds.Tables[0];
grid.DataBind();
sqlConn.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
bind();
if (!Page.IsPostBack)
{
bind();
}
}
is wrong.
It should be:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bind();
}
}
On Pageload put your bind grid code in following condition
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bind();
}
}
You need to call GridView1.DataBind() in the end.

sort Gridview doesn't work

I have asp.net page contain gridview as following
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
OnPageIndexChanging="gridView_PageIndexChanging"
OnSorting="TaskGridView_Sorting"
AllowSorting="True" AutoGenerateColumns="False"
onselectedindexchanged="GridView1_SelectedIndexChanged"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
CellPadding="3" CellSpacing="2">
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<Columns>
<asp:boundfield datafield="name_english" convertemptystringtonull="true" headertext="Name"/>
<asp:BoundField DataField="Inc_ID" convertemptystringtonull="true" HeaderText="Inc_ID" SortExpression="Inc_ID"/>
<asp:BoundField DataField="UID" HeaderText="Study_UID" SortExpression= "UID"/>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>
I fill and sort it using the following code
protected void Button1_Click(object sender, EventArgs e)
{
//connection to database
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["NorthindConnectionString"].ConnectionString;
SqlConnection myConn = new SqlConnection(connection);
myConn.Open();
SqlCommand cmd = new SqlCommand(" WorkList", myConn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#Name", TextBox1.Text));
cmd.Parameters.Add(new SqlParameter("#ID", TextBox2.Text));
cmd.Parameters.Add(new SqlParameter("#AccNo", TextBox4.Text));
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
Session["TaskTable"] = ds.Tables[0];
ds.Dispose();
da.Dispose();
GridView1.Visible = true;
myConn.Close();
}
protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = Session["TaskTable"] as DataTable;
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
GridView1.DataSource = Session["TaskTable"];
GridView1.DataBind();
}
}
private string GetSortDirection(string column)
{
// By default, set the sort direction to ascending.
string sortDirection = "ASC";
// Retrieve the last column that was sorted.
string sortExpression = ViewState["SortExpression"] as string;
if (sortExpression != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection = "DESC";
}
}
}
// Save new values in ViewState.
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
return sortDirection;
}
}
the problem when click on any header for sorting raise error System.IndexOutOfRangeException: Cannot find column name .. , any idea to solve that , I am sure from the columns name in database ,
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = gridView.DataSource as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
gridView.DataSource = dataView;
gridView.DataBind();
}
}
try this code..
You need to bind your grid to the sorted view (and not the original table) for sorting to work.
protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = Session["TaskTable"] as DataTable;
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression;
GridView1.DataSource = dt.DefaultView;
GridView1.DataBind();
}
}
I am not sure if you need GetSortDirection method.
Also note that SortExpression property consists of sort direction (e.g. "UID DESC") so base your logic on that. Your code could have set sort expression such as "UID DESC ASC" which is obviously a wrong expression.
In order to have the code work in asp.net or a web environment, you need to put your gridview in Session a session object, and your sorting in a view state. In order to get the sorting to work with paging, do the following.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["SearchTable"] = gv_GridView.DataSource;
LoadSearchGrid("Select * from WF_Search);
}
private void LoadSearchGrid(string query)
{
DataTable dsp = new DataTable();
conn = new SqlConnection(ConnectionString);
SqlDataAdapter sda = new SqlDataAdapter(query, conn);
conn.Open();
sda.Fill(dsp);
Session["SearchTable"] = dsp;
gv_GridView.DataSource = Session["SearchTable"];
gv_GridView.DataBind();
conn.Close();
sda.Dispose();
}
protected void gv_GridView_Sorting(object sender, GridViewSortEventArgs e)
{
ViewState["SortDirection"] = e.SortDirection;
DataTable dtr = Session["SearchTable"] as DataTable;
if (dtr != null)
{
dtr.DefaultView.Sort = e.SortExpression + " " + getSortDirection(e.SortExpression);
gv_GridView.DataSource = Session["SearchTable"];
gv_GridView.DataBind();
Session["SearchTable"] = gv_GridView.DataSource;
}
}
private string getSortDirection(string column)
{
string sortDirection = "ASC";
string sortExpression = ViewState["SortDirection"] as string;
if (sortExpression != null)
{
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if (lastDirection != null && lastDirection == "ASC")
{
sortDirection = "DESC";
}
}
}
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
return sortDirection;
}
protected void gv_GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gv_GridView.DataSource = Session["SearchTable"];
gv_GridView.DataBind();
gv_GridView.PageIndex = e.NewPageIndex;
}

Categories

Resources