add rows in dataTable from different buttons asp.net] - asp.net

Hello i have problem with data Table. I want to insert new row in data Table every time when user click on button.I have 10 buttons and when user click on button 1,it insert new row but when user clicks on button 2 existing row is replaced with new one. HELP!
////here i call methods for adding new rows from button clicks
private void RemoveDuplicates (Data_Table dt)
{
if (ViewState["Markici"] != null)
{
dtCurrentTable = (DataTable)ViewState["Markici"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = dtCurrentTable.Rows.Count - 1; i >= 0; i--)
{
if (i == 0)
{
break;
}
for (int j = i - 1; j >= 0; j--)
{
if (dtCurrentTable.Rows[i]["Cena1"].ToString() == dtCurrentTable.Rows[j]["Cena1"].ToString())
{
dtCurrentTable.Rows[i].Delete();
break;
}
}
}
}
dtCurrentTable.AcceptChanges();
// ViewState["Markici"] = dtCurrentTable;
// Repeater1.DataSource = dtCurrentTable;
// Repeater1.DataBind();
AddNewRecordRowToGrid();
AddNewRecordRowToGridf();
decimal vkupno = 0m;
vkupno += Convert.ToDecimal(Label6.Text);
decimal vkupno2 = 0m;
vkupno2 += Convert.ToDecimal(Label17.Text);
vkupno += vkupno2;
Label26.Text = vkupno.ToString();
//xml table
// DataSet ds = new DataSet();
// ds.Tables.Add(dtCurrentTable);
//binding Gridview with New Row
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
}
//method for adding row, call this in button click 9
private void AddNewRecordRowToGrid()
{
int counter;
if (Request.Cookies["kasa"] == null)
counter = 0;
else
{
counter = int.Parse(Request.Cookies["kasa"].Value);
}
counter++;
Response.Cookies["kasa"].Value = counter.ToString();
Response.Cookies["kasa"].Expires = DateTime.Now.AddYears(2);
if (ViewState["Markici"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["FirmaID"] = Request.Cookies["firma"].Value;
drCurrentRow["Godina"] = Request.Cookies["godina"].Value;
drCurrentRow["KasaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["MarkicaID"] = counter;
drCurrentRow["Datum"] = DateTime.Now;
drCurrentRow["Masa"] = Session["masa39"];
drCurrentRow["VrabotenID"] = Session["New"];
drCurrentRow["Artikal"] = Label3.Text;
drCurrentRow["Cena1"] = Label4.Text;
drCurrentRow["Kolicina"] = Label5.Text;
drCurrentRow["Smena"] = Session["smena1"];
drCurrentRow["VkIznos"] = Label6.Text;
drCurrentRow["VkDanok"] = Label8.Text;
drCurrentRow["SySDatum"] = DateTime.Now;
drCurrentRow["Vid"] = Label23.Text;
drCurrentRow["Edmera"] = Label10.Text;
drCurrentRow["ArtikalID"] = Label33.Text;
}
/*
for (int i = 0; i < dtCurrentTable.Rows.Count; i++)
{
if (dtCurrentTable.Rows[i].IsNull(0) == true)
{
dtCurrentTable.Rows[i].Delete();
dtCurrentTable.AcceptChanges();
}
}*/
//Removing initial blank row
if (dtCurrentTable.Rows[0][0].ToString() == "")
{
dtCurrentTable.Rows[0].Delete();
dtCurrentTable.AcceptChanges();
}
//Added New Record to the DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//storing DataTable to ViewState
ViewState["Markici"] = dtCurrentTable;
//binding Gridview with New Row
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
}
}
// call this in button 10 click
private void AddNewRecordRowToGridf()
{
if (ViewState["Markici"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//Creating new row and assigning values
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["FirmaID"] = Request.Cookies["firma"].Value;
drCurrentRow["Godina"] = Request.Cookies["godina"].Value;
drCurrentRow["KasaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["MarkicaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["Datum"] = DateTime.Now;
drCurrentRow["Masa"] = Session["masa39"];
drCurrentRow["VrabotenID"] = Session["New"];
drCurrentRow["Artikal"] = Label12.Text;
drCurrentRow["Cena1"] = Label13.Text;
drCurrentRow["Kolicina"] = Label11.Text;
drCurrentRow["Smena"] = Session["smena1"];
drCurrentRow["VkIznos"] = Label17.Text;
drCurrentRow["VkDanok"] = Label18.Text;
drCurrentRow["SySDatum"] = DateTime.Now;
drCurrentRow["Vid"] = Label24.Text;
drCurrentRow["Edmera"] = Label16.Text;
drCurrentRow["ArtikalID"] = Label34.Text;
}
for (int i = 0; i < dtCurrentTable.Rows.Count; i++)
{
if (dtCurrentTable.Rows[i].IsNull(0) == true)
{
dtCurrentTable.Rows[i].Delete();
dtCurrentTable.AcceptChanges();
}
}
/*
//Removing initial blank row
if (dtCurrentTable.Rows[0][0].ToString() == "")
{
dtCurrentTable.Rows[0].Delete();
dtCurrentTable.Rows[1].Delete();
dtCurrentTable.AcceptChanges();
}
*/
//Added New Record to the DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//storing DataTable to ViewState
ViewState["Markici"] = dtCurrentTable;
//binding Gridview with New Row
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
}
protected void Button9_Click(object sender, EventArgs e)
{
RemoveDuplicates(dt);
}
protected void Button10_Click(object sender, EventArgs e)
{
RemoveDuplicates(dt);
}
// create DataTable
private void AddDefaultFirstRecord()
{
//creating DataTable
DataTable dt = new DataTable();
DataRow dr;
dt.TableName = "Markici";
//creating columns for DataTable
dt.Columns.Add(new DataColumn("FirmaID", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("Godina", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("KasaID", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("MarkicaID", typeof(System.Int64)));
dt.Columns.Add(new DataColumn("Datum", typeof(System.DateTime)));
dt.Columns.Add(new DataColumn("Masa", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("VrabotenID", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("Artikal", typeof(System.String)));
dt.Columns.Add(new DataColumn("Cena1", typeof(System.String)));
dt.Columns.Add(new DataColumn("Kolicina", typeof(System.Decimal)));
dt.Columns.Add(new DataColumn("Smena", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("VkIznos", typeof(System.Decimal)));
dt.Columns.Add(new DataColumn("VkDanok", typeof(System.Decimal)));
dt.Columns.Add(new DataColumn("SysDatum", typeof(System.DateTime)));
dt.Columns.Add(new DataColumn("Vid", typeof(System.String)));
dt.Columns.Add(new DataColumn("EdMera", typeof(System.String)));
dt.Columns.Add(new DataColumn("ArtikalID", typeof(System.String)));
dr = dt.NewRow();
dt.Rows.Add(dr);
ViewState["Markici"] = dt;
GridView2.DataSource = dt;
GridView2.DataBind();
}

Add dtCurrentTable.AcceptChanges(); after dtCurrentTable.Rows.Add(drCurrentRow);
Don't keep a DataTable in to ViewState. DataTable is a big object. It will affect page performance. You can keep in to cache or session.
My recomandation is to cache the datatable datasource not the datatable object.

Related

Dealing with Empty cells from Excel export

I have an export function in my asp.net application. I want to remove all the white spaces/nulls in the list. Any way to trim it?
This is how my code looks like:
My GetData methode from the Database:
public void GetData()
{
try
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["GS1connectionString"].ConnectionString);
connection.Open();
using (SqlCommand sqlCmd = new SqlCommand("DAtabase.dbo.SP_EXPORT", connection)) //Extract data: no cons first and cons after
{
sqlCmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
Session["TaskTable"] = dt;
}
}
}
}
catch (Exception)
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('No data found, try again');", true);
}
}
Clean dataTable methode:
public DataTable removeEmptyColumns(DataTable table)
{
int k = 0, l = 0;
DataTable dtResult = table.Clone();
DataRow row = dtResult.NewRow();
row = dtResult.NewRow();
for (k = 0; k < table.Rows.Count; k++)
{
for (l = 0; l < table.Rows.Count; l++)
{
if (k == l)
row[k] = table.Rows[k][l];
}
}
dtResult.Rows.Add(row);
dtResult.AcceptChanges();
return dtResult;
}
The Export to excel button:
protected void Button_Export_DS_Click(object sender, EventArgs e)
{
GetData();
DataTable dat = new DataTable();
DataTable dtNew = new DataTable();
dat = (DataTable)Session["TaskTable"];
dtNew = removeEmptyColumns(dat);
//Export to excel from datatable stored in a session
if (dtNew.Rows.Count > 0)
{
MemoryStream ms = new MemoryStream();
int i = 1;
using (ExcelPackage package = new ExcelPackage(ms))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet" + i++);
worksheet.Cells["A1"].LoadFromDataTable(dtNew, true);
worksheet.Cells.AutoFitColumns();
Response.Clear();
package.SaveAs(Response.OutputStream);
Response.AddHeader("content-disposition", "attachchment; filename=DS_Export.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
Response.End();
}
}
}
I have an export function in my asp.net application. I want to remove all the white spaces/nulls in the list. Any way to trim it?
You copy and paste this function:
public DataTable removeEmptyColumns(DataTable table)
{
int k = 0, l = 0;
DataTable dtResult = table.Clone();
DataRow row = dtResult.NewRow();
row = dtResult.NewRow();
for (k = 0; k < table.Rows.Count ; k++)
{
for (l = 0; l < table.Rows.Count; l++)
{
if (k == l)
row[k] = table.Rows[k][l];
}
}
dtResult.Rows.Add(row);
dtResult.AcceptChanges();
return dtResult;
}
And then use the function like this:
DataTable dt = new DataTable();
DataTable dtNew = new DataTable();
dt = (DataTable)Session["TaskTable"];
dtNew = removeEmptyColumns(dt);
After that, use this dtNew in this:
if (dtNew.Rows.Count > 0)
{
MemoryStream ms = new MemoryStream();
int i = 1;
using (ExcelPackage package = new ExcelPackage(ms))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet" + i++);
worksheet.Cells["A1"].LoadFromDataTable(dtNew, true);
worksheet.Cells.AutoFitColumns();
Response.Clear();
package.SaveAs(Response.OutputStream);
Response.AddHeader("content-disposition", "attachchment; filename=Export.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
Response.End();
}
}

I have to click twice a link button to change page

I have to click linkbutton twice to change the page and load subfolders of current folder. I think I have some problems with my session and event.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TableRow r = new TableRow();
TableCell c1 = new TableCell();
LinkButton l = new LinkButton();
var strarray = Server.MapPath(Session["url"].ToString()).Split(Path.DirectorySeparatorChar);
Table table = new Table();
l.ID = "lable" + table.Rows.Count;
l.Text = strarray.Last();
l.EnableViewState = true;
r.ID = "newRow" + table.Rows.Count;
c1.ID = "newC1" + table.Rows.Count;
c1.Controls.Add(l);
r.Cells.Add(c1);
table.Rows.Add(r);
this.form1.Controls.Add(table);
}
else
{
if(Directory.Exists(Server.MapPath(Session["url"].ToString())))
{
string[] allFolders = Directory.GetDirectories(Server.MapPath(Session["url"].ToString()));
Table table = new Table();
foreach (string str in allFolders)
{
TableRow r = new TableRow();
TableCell c1 = new TableCell();
LinkButton l = new LinkButton();
var strarray = str.Split(Path.DirectorySeparatorChar);
l.ID = strarray.Last();
l.CommandName = "createLink";
l.Click+= new EventHandler(LinkButton_Command);
l.Text = strarray.Last();
l.EnableViewState = true;
r.ID = "newRow" + table.Rows.Count;
c1.ID = "newC1" + table.Rows.Count;
c1.Controls.Add(l);
r.Cells.Add(c1);
table.Rows.Add(r);
this.form1.Controls.Add(table);
}
}
else
{
Work work=new Work();
work.SetFolder(Session["url"].ToString());
work.CreateFolder();
}
}
}
public void LinkButton_Command(object sender, EventArgs e)
{
Session["url"] = Session["url"] + "\\" + ((LinkButton)sender).ID;
}
I think this is because the Page_Load() method is called before the LinkButton_Command(). The session variable Session["url"] still contains the previous value when the code in Page_Load() executes.
Try moving the code from the else-branch of Page_Load() at the end of LinkButton_Command().
after mix up your answer and my program , come to a answer that will work.
protected void Page_Load(object sender, EventArgs e)
{
if (Directory.Exists(Server.MapPath(Session["url"].ToString())))
{
string[] allFolders = Directory.GetDirectories(Server.MapPath(Session["url"].ToString()));
Table table = new Table();
foreach (string str in allFolders)
{
TableRow r = new TableRow();
TableCell c1 = new TableCell();
LinkButton l = new LinkButton();
var strarray = str.Split(Path.DirectorySeparatorChar);
l.ID = strarray.Last();
l.CommandName = "createLink";
l.Click += new EventHandler(LinkButton_Command);
l.Text = strarray.Last();
l.EnableViewState = true;
r.ID = "newRow" + table.Rows.Count;
c1.ID = "newC1" + table.Rows.Count;
c1.Controls.Add(l);
r.Cells.Add(c1);
table.Rows.Add(r);
this.form1.Controls.Clear();
this.form1.Controls.Add(table);
}
}
}
public void LinkButton_Command(object sender, EventArgs e)
{
Session["url"] = Session["url"] + "\\" + ((LinkButton)sender).ID;
if (Directory.Exists(Server.MapPath(Session["url"].ToString())))
{
string[] allFolders = Directory.GetDirectories(Server.MapPath(Session["url"].ToString()));
Table table = new Table();
foreach (string str in allFolders)
{
TableRow r = new TableRow();
TableCell c1 = new TableCell();
LinkButton l = new LinkButton();
var strarray = str.Split(Path.DirectorySeparatorChar);
l.ID = strarray.Last();
l.CommandName = "createLink";
l.Click += new EventHandler(LinkButton_Command);
l.Text = strarray.Last();
l.EnableViewState = true;
r.ID = "newRow" + table.Rows.Count;
c1.ID = "newC1" + table.Rows.Count;
c1.Controls.Add(l);
r.Cells.Add(c1);
table.Rows.Add(r);
this.form1.Controls.Clear();
this.form1.Controls.Add(table);
}
}
}

Filling data in grid view using textbox on button click -it show an a error inder out of bound

when i used a textbox to insert data it show index out of bound error
Button_Click()
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Name"); ///enter code here
dt.Columns.Add("Address");
dt.Columns.Add("Number");
//First fill all the date present in the grid
for (int intCnt = 0; intCnt < grd.Rows.Count; intCnt ++)
{
if (grd.Rows[intCnt].RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Name"] = grd.Rows[intCnt].Cells[0].Value;/// at this point
dr["Address"] = grd.Rows[intCnt].Cells[1].Value;
dr["Number"] = grd.Rows[intCnt].Cells[2].Value;
dt.Rows.Add(dr);
}
}
dr = dt.NewRow();
dr["Name"] = txt1.Text;
dr["Address"] = txt2.Text;
dr["Number"] = txt3.Text;
dt.Rows.Add(dr);
grd.DataSource = dt;
grd.DataBind();
}
Try this
You have to use grd.Rows.Count-1 in for loop
Button_Click()
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Name");
dt.Columns.Add("Address");
dt.Columns.Add("Number");
for (int intCnt = 0; intCnt < grd.Rows.Count-1; intCnt ++)
{
if (grd.Rows[intCnt].RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Name"] = grd.Rows[intCnt].Cells[0].Value;/// at this point
dr["Address"] = grd.Rows[intCnt].Cells[1].Value;
dr["Number"] = grd.Rows[intCnt].Cells[2].Value;
dt.Rows.Add(dr);
}
}
dr = dt.NewRow();
dr["Name"] = txt1.Text;
dr["Address"] = txt2.Text;
dr["Number"] = txt3.Text;
dt.Rows.Add(dr);
grd.DataSource = dt;
grd.DataBind();
}
Hope this help you
change the condition of your for loop to be for (int intCnt = 0; intCnt < grd.Rows.Count-1; intCnt ++)
{...}
instead of for (int intCnt = 0; intCnt < grd.Rows.Count; intCnt ++)
{...}

Adding new row to listview removes above selected dropdown Clearing

When i add the new row to the List view above selected dropdownlist gets cleared .what is the reason for this problem plz suggest me
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
FirstListViewRow();
BindDataToGridviewDropdownlist();
}
}
protected void BindDataToGridviewDropdownlist()
{
DataSet dsDept = new DataSet();
dsDept.ReadXml(Server.MapPath("XMLFile2.xml"));
DataView dv = dsDept.Tables[0].DefaultView;
foreach (var list in listview1.Items)
{
if (list.ItemType == ListViewItemType.DataItem)
{
DropDownList ddf = (DropDownList)list.FindControl("ddldatatype");
ddf.DataSource = dv;
ddf.DataTextField = "value";
ddf.DataBind();
ddf.Items.Insert(0, new ListItem("--Select--", "0"));
}
}
}
private void FirstListViewRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("OrderNo", typeof(string)));
dt.Columns.Add(new DataColumn("ColumnTitle", typeof(string)));
dt.Columns.Add(new DataColumn("Datatype", typeof(string)));
dt.Columns.Add(new DataColumn("Examples", typeof(string)));
dt.Columns.Add(new DataColumn("Options", typeof(string)));
dt.Columns.Add(new DataColumn("Delete", typeof(string)));
dr = dt.NewRow();
dt.Rows.Add(dr);
dr["OrderNo"] = 1;
Session["CurrentTable"] = dt;
listview1.DataSource = dt;
listview1.DataBind();
}
private void AddNewRow()
{
int rowIndex = 0;
if (Session["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)Session["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
Label TextBoxorder = (Label)listview1.Items[rowIndex].FindControl("txtorder");
TextBox TextBoxcolumnname = (TextBox)listview1.Items[rowIndex].FindControl("txtcolumnname");
DropDownList DropDatatype = (DropDownList)listview1.Items[rowIndex].FindControl("ddldatatype");
DropDownList Dropexample = (DropDownList)listview1.Items[rowIndex].FindControl("ddlexamples");
TextBox TextBoxoptions = (TextBox)listview1.Items[rowIndex].FindControl("txtoptions");
CheckBox Checkdel = (CheckBox)listview1.Items[rowIndex].FindControl("chkdel");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["OrderNo"] = i + 1;
// dtCurrentTable.Rows[i - 1]["Order"] = TextBoxorder.Text;
dtCurrentTable.Rows[i - 1]["ColumnTitle"] = TextBoxcolumnname.Text;
dtCurrentTable.Rows[i - 1]["Datatype"] = DropDatatype.Text;
dtCurrentTable.Rows[i - 1]["Examples"] = Dropexample.Text;
dtCurrentTable.Rows[i - 1]["Options"] = TextBoxoptions.Text;
dtCurrentTable.Rows[i - 1]["Delete"] = Checkdel.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
Session["CurrentTable"] = dtCurrentTable;
listview1.DataSource = dtCurrentTable;
listview1.DataBind();
Label txn = (Label)listview1.Items[rowIndex].FindControl("txtorder");
txn.Focus();
}
}
else
{
Response.Write("Session is null");
}
BindDataToGridviewDropdownlist();
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
AddNewRow();
}
protected void btndelete_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (Session["CurrentTable"] != null)
{
dt = (DataTable)Session["CurrentTable"];
int j = 0;
for (int i = 0; i < listview1.Items.Count; i++)
{
ListViewDataItem items = listview1.Items[i];
CheckBox chkBox = (CheckBox)items.FindControl("chkdel");
if (chkBox.Checked == true)
{
dt.Rows.RemoveAt(j);
dt.AcceptChanges();
}
else
{
j++;
}
}
Session["CurrentTable"] = dt;
listview1.DataSource = dt;
listview1.DataBind();
BindDataToGridviewDropdownlist();
}
}
protected void btnClear_Click(object sender, EventArgs e)
{
listview1.Items.Clear();
}
}
}
Add a property DataKeyNames in this ListView like this:
<asp:listview id="listview1" runat="server" datakeynames="Datatype" xmlns:asp="#unknown"></asp:listview>
and add these lines inside BindDataToGridviewDropdownlist method:
ListViewDataItem di = (ListViewDataItem)list;
string dataType = listview1.DataKeys[di.DisplayIndex].Values[0].ToString();
ddf.SelectedValue = dataType;
here is how you BindDataToGridviewDropdownlist method would look like:
protected void BindDataToGridviewDropdownlist()
{
DataSet dsDept = new DataSet();
dsDept.ReadXml(Server.MapPath("XMLFile2.xml"));
DataView dv = dsDept.Tables[0].DefaultView;
foreach (var list in listview1.Items)
{
if (list.ItemType == ListViewItemType.DataItem)
{
DropDownList ddf = (DropDownList)list.FindControl("ddldatatype");
ddf.DataSource = dv;
ddf.DataTextField = "value";
ddf.DataBind();
ddf.Items.Insert(0, new ListItem("--Select--", "0"));
ListViewDataItem di = (ListViewDataItem)list;
string dataType = listview1.DataKeys[di.DisplayIndex].Values[0].ToString();
ddf.SelectedValue = dataType;
}
}
}

how to do gridview sorting without data Source?

i am trying to do sorting and paging for my gridview without datasource but when i click on the header of the gridview to sort it , nothing happen but when i click for paging is working fine and there is no error. how to do about it?
this is my code:
protected void Page_Load(object sender, EventArgs e)
{
dbBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dtSortTable = GridView1.DataSource as DataTable;
if (dtSortTable != null)
{
DataView dvSortedView = new DataView(dtSortTable);
dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection);
GridView1.DataSource = dvSortedView;
GridView1.DataBind();
}
}
private string getSortDirectionString(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
if(sortDirection== SortDirection.Ascending)
{
newSortDirection = "ASC";
}
else
{
newSortDirection = "DESC";
}
return newSortDirection;
}
private void dbBind()
{
DataSet ds;
string startdate = (string)(Session["startdate"]);
string enddate = (string)(Session["enddate"]);
var format = "dd/MM/yyyy";
DateTime one = DateTime.ParseExact(startdate, format, CultureInfo.InvariantCulture);
DateTime two = DateTime.ParseExact(enddate, format, CultureInfo.InvariantCulture);
if (two >= one)
{
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=n;Integrated Security=True");
//conn.Open();
SqlCommand cmd = new SqlCommand("SELECT [AmountSpent], [TimeDate]=convert(nvarchar,timedate,103), [StallNo] FROM [StudentTransactions] WHERE TimeDate BETWEEN #one AND #two", conn);
cmd.Parameters.AddWithValue("#one", one);
cmd.Parameters.AddWithValue("#two", two);
ds = new DataSet();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(ds);
if (ds.Tables.Count > 0)
{
DataView dv = ds.Tables[0].DefaultView;
if (ViewState["SortDirection"] != null)
{
sortDirection = ViewState["SortDirection"].ToString();
}
if (ViewState["SortExpression"] != null)
{
sortExpression = ViewState["SortExpression"].ToString();
dv.Sort = string.Concat(sortExpression, " ", sortDirection);
}
GridView1.DataSource = dv;
GridView1.DataBind();
}
}
//GridView1.DataBind();
//conn.Close();
}
else
{
GridView1.Visible = false;
string strMsg = " Data not found for the choosen dates.";
Response.Write("<script>alert('" + strMsg + "')</script>");
}
}

Resources