paging and sorting in grid view - asp.net

i have a code performing paging and sorting in grid view.
(bing_grid is user defined function)
public void bind_grid()
{
con = new SqlConnection();
con.ConnectionString = "Data Source=STIRAPC105;InitialCatalog=anitha;Integrated Security=True";
con.Open();
SqlDataAdapter sqa = new SqlDataAdapter("select * from employees", con);
DataSet ds = new DataSet();
sqa.Fill(ds);
DataTable mytab = ds.Tables[0];
GridView1.DataSource = mytab;
GridView1.DataBind();
//con.Close();
}
code for paging
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bind_grid();
}
code for sorting
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = GridView1.DataSource as DataTable;
if (dt != null)
{
DataView dataview = new DataView(dt);
dataview.Sort = e.SortExpression + " " + sort_grid(e.SortDirection);
GridView1.DataSource = dataview;
GridView1.DataBind();
}
}
user defined code for sorting
public string sort_grid()
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
paging works, Errors was:
1. "no overload for method 'sort_grid' takes 1 argument" (dataview.Sort = e.SortExpression + " " + sort_grid(e.SortDirection);)
2.The name 'sortDirection does not exist in the current context. (switch (sortDirection))
Help me friends.

this method:
public string sort_grid()
takes no arguments but you are trying to call it with e.SortDirection:
dataview.Sort = e.SortExpression + " " + sort_grid(e.SortDirection);
You must change the signature of sort_grid() to
sort_grid(SortDirection sortDirection)
This will also solve your second problem, which you are trying to use sortDirection variable, before declaring it in the method sort_grid.

Related

Returning output values from a stored procedure to asp.net

I have an output value in my procedure called result, I want to make an if condition in asp.net that checks if result = 1 and print a statement
public partial class ManagerViewTasks : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection( #"data source= DODO\SQLEXPRESS; " +
"Initial Catalog = Company_103; Integrated Security = True");
protected void Button1_Click(object sender, EventArgs e)
{
if (sqlcon.State == System.Data.ConnectionState.Closed)
sqlcon.Open();
SqlCommand sqlcmd = new SqlCommand("MG_Reviews_Task",sqlcon);
sqlcmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlcmd.Parameters.Add("#result ", SqlDbType.Int).Direction=ParameterDirection.Output;
sqlcmd.Parameters.AddWithValue("#re ", Txtname.Text.Trim());
sqlcmd.Parameters.AddWithValue("#task", TextBox2.Text.Trim());
sqlcmd.Parameters.AddWithValue("#proj",TextBox3.Text.Trim());
sqlcmd.Parameters.AddWithValue("#company",TextBox4.Text.Trim());
sqlcmd.Parameters.AddWithValue("#manager",TextBox5.Text.Trim());
sqlcmd.Parameters.AddWithValue("#res",TextBox6.Text.Trim());
sqlcmd.Parameters.AddWithValue("#deadline ",TextBox7.Text.Trim());
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
}
}
SqlParameter result = New SqlParameter();
result.ParameterName = "result";
result.Value = 0;
result.Size = 1;
result.Direction = ParameterDirection.Output;
sqlcmd.Parameters.Add(result);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
//Check result value here
if (result.value == 1){
//Do something;
}

Grid View only updates when page refresh

In my application i have a grid view and a save task button. when i click save task my button , the Grid View doesn't refresh but when i click the refresh button of browser the grid refreshes and automatically add another task in the database. All i want is to refresh the grid when save task button is click and not add task when browser refresh button is clicked.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
static string startdate;
DataTable dt;
static string enddate;
static string EstDate;
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
protected void Page_Load(object sender, EventArgs e)
{//Page dosn't go back//
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetNoStore();
if (IsPostBack)
{
if (Session["auth"] != "ok" )
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
//Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
else
{
GridView1.DataSource = dt;
GridView1.DataBind();
if (Session["auth"] != "ok")
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
// Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
//decode url data in query string
labelID.Text = HttpUtility.UrlDecode(Request.QueryString["Id"]);
labelDur.Text = HttpUtility.UrlDecode(Request.QueryString["Duration"]);
labelStatus.Text = HttpUtility.UrlDecode(Request.QueryString["Status"]);
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
if (!IsPostBack)
{
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
}
protected void saveTask_Click(object sender, EventArgs e)
{
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
try
{
String query = "insert into Tasks (T_Description, T_Status,S_ID,StartDate,EstEndDate) values('" + TaskDesBox.Text + "', 'incomplete','" + labelID.Text + "' ,'" + startdate + "','" + EstDate + "');";
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
GridView1.DataBind();
}
else
{
TaskStatus.Text = "Task not Saved";
}
}
catch (Exception ex)
{
Response.Write("reeor" + ex);
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void TaskDesBox_TextChanged(object sender, EventArgs e)
{
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Calendar1.Visible = true;
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
startdate = Calendar1.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
SDate.Text = startdate;
Calendar1.Visible = false;
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
Calendar2.Visible = true;
}
protected void Calendar2_SelectionChanged(object sender, EventArgs e)
{
EstDate = Calendar2.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
EstDateBox.Text = EstDate;
Calendar2.Visible = false;
}
}
What you are doing on a post back is:
First show the results due to code in your Page_Load
Then perform event handlers, so if you pushed the Save button, the saveTask_Click will be performed, which adds a record to the database. You don't update your grid view datasource, but just call DataBind() afterwards which still binds the original DataSource.
Imo you shouldn't update your grid view on Page_Load. You should only show it initially on the GET (!IsPostBack).
And at the end of saveTask_Click you have to update your grid view again.
So move the code you need to show the grid view to a method you can call on other occasions:
protected void ShowGridView() {
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
Then call it in your Page_Load on !IsPostBack
if (!IsPostBack)
{
ShowGridView();
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
Then after adding the row in saveTask_Click you can call ShowGridView() to see the new result.
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
//GridView1.DataBind();
ShowGridView();
}
else
{
TaskStatus.Text = "Task not Saved";
}

Gridview does not show SQL Server database records

I'm designing a web system for my fyp.
I use SqlDependency to get table change info from cache.
I used SqlDataAdapter, dataSet and gridview, but it doesn't show any result on screen.
Can you tell me where the problem is in my code?
protected void refresh_Click(object sender, EventArgs e)
{
if (Cache["shipOrders"] == null)
{
gvshipOrders.DataSource = Cache["shipOrders"];
gvshipOrders.DataBind();
lblOrderNotification.Text = "last order recived at " + DateTime.Now.ToString();
}
else
{
string xconnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
SqlConnection sqlCon = new SqlConnection(xconnectionString);
SqlDataAdapter da = new SqlDataAdapter("viewOrders", sqlCon);
DataSet ds = new DataSet();
da.Fill(ds);
SqlCacheDependency XsqlcacheDependecy = new SqlCacheDependency("secaloTest1", "customerShipOrder");
//caching shipOrders table data
/*
Cache.Insert("shipOrders", ds, null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
another overloaded method is used */
Cache.Insert("shipOrders", ds, XsqlcacheDependecy);
gvshipOrders.DataSource = ds;
gvshipOrders.DataBind();
lblOrderNotification.Text = "orders retrived from database at " + DateTime.Now.ToString();
}
}
I've found the problem,
public partial class OrderProccessing : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["email"] == null)
{
Response.Redirect("Default.aspx");
}
else
{
string value = Session["email"].ToString();
Classes.AddAddress addcuid = new Classes.AddAddress(value);
txtstaffname.Text = addcuid.addStaffName().ToString();
txtstaffID.Text = addcuid.fetchStaffID().ToString();
}
}
protected void refresh_Click(object sender, EventArgs e)
{
if (Cache["shipOrders"] != null)
{
myGrid.DataSource = Cache["ShipOrders"];
myGrid.DataBind();
lblOrderNotification.Text = "last order recived at " + DateTime.Now.ToString();
}
else
{
string xconnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
SqlConnection sqlCon = new SqlConnection(xconnectionString);
SqlDataAdapter da = new SqlDataAdapter("viewOrders", sqlCon);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
SqlCacheDependency XsqlcacheDependecy = new SqlCacheDependency("secaloTest1", "customerShipOrder");
//caching shipOrders table data
/*
Cache.Insert("shipOrders", ds, null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
another overloaded method is used */
Cache.Insert("shipOrders", ds, XsqlcacheDependecy);
myGrid.DataSource = ds;
myGrid.DataBind();
lblOrderNotification.Text = "orders retrived from database at " + DateTime.Now.ToString();
}
}
}

System.NullReferenceException: Object reference not set to an instance of an object:

I am new in asp.net and working on the data grid view in asp.net.i have written the following code for inserting and updating the columns in grid view.the grid is showing the data very well,but when i am trying to edit any row in the grid then it is throwing an Exception:
System.NullReferenceException: Object reference not set to an instance of an object: in the following line:
string UpdateQuery = string.Format("UPDATE tbl_PaperRateList set rate=" + rate1.Text + " where companyId=" + company_id.Text + " and paperId=" +paper_id.Text+ "");
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["con"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
protected void gridRateList_RowEditing(object sender, GridViewEditEventArgs e)
{
gridRateList.EditIndex = e.NewEditIndex;
BindGridData();
}
protected void gridRateList_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gridRateList.EditIndex = -1;
BindGridData();
}
#endregion
#region Binding the RateList Grid
public void BindGridData()
{
{
conn.Open();
SqlCommand cmdCompanyId = new SqlCommand("Select max(companyId) from tbl_PaperRateList", conn);
int c_id = Convert.ToInt32(cmdCompanyId.ExecuteScalar());
using (SqlCommand comm = new SqlCommand("select p.paperId,"
+ "p.Rate,pm.PaperName from tbl_PaperRatelist p,tbl_papermaster pm where p.paperId=pm.paperId and p.companyId=" + c_id + "", conn))
{
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
gridRateList.DataSource = ds;
gridRateList.DataBind();
}
}
}
#endregion
#region /*Updating the Row in Grid View*/
protected void gridRateList_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string s = gridRateList.DataKeys[e.RowIndex].Value.ToString();
Label company_id = (Label)gridRateList.Rows[e.RowIndex].FindControl("CompanyId");
Label paper_id = (Label)gridRateList.Rows[e.RowIndex].FindControl("paperId");
TextBox rate1 = (TextBox)gridRateList.Rows[e.RowIndex].FindControl("txtRate");
string UpdateQuery = string.Format("UPDATE tbl_PaperRateList set rate=" + rate1.Text + " where companyId=" + company_id.Text + " and paperId=" +paper_id.Text+ "");
gridRateList.EditIndex = -1;
BindGridData(UpdateQuery);
}
#endregion
#region Bind the Gridview after updating the row
private void BindGridData(string Query)
{
string connectionstring = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionstring))
{
conn.Open();
SqlCommand cmdCompanyId = new SqlCommand("Select max(companyId) from tbl_PaperRateList", conn);
int cid = Convert.ToInt32(cmdCompanyId.ExecuteScalar());
using (SqlCommand comm = new SqlCommand(Query +
";select p.paperId,"
+ "p.Rate,pm.PaperName from tbl_PaperRatelist p,tbl_papermaster pm where p.paperId=pm.paperId and p.companyId=" + cid + "", conn))
{
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
gridRateList.DataSource = ds;
gridRateList.DataBind();
}
}
}
#endregion
}
Did u declared globally or assigned null value to the variable..?
like this string UpdateQuery="";
Check the rate1.Text,company_id.Text ,paper_id.Text properties getting values or not.
Debug the Function BindGridData(string Query) the error happening there i think. check the parameters of that function. some parameters getting null value that's what the Exception is coming. check it out.
Hope this may helpful....
Did u declared globally or assigned null value to the variable..?
like this string UpdateQuery="";
Check the rate1.Text,company_id.Text ,paper_id.Text properties getting values or not.
Debug the Function BindGridData(string Query) the error happening there i think. check the parameters of that function. some parameters getting null value that's what the Exception is coming. check it out.

Grid view Updatearguments does Not contain New Values

public partial class Gridvw_expt2 : System.Web.UI.Page
{
SqlCommand com;
SqlDataAdapter da;
DataSet ds;
SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["gj"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
com = new SqlCommand("Select * from tblExpt",con);
da = new SqlDataAdapter(com);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows[0] != null)
{
GridView1.AutoGenerateEditButton = true;
GridView1.DataSource = ds;
GridView1.DataBind();
GridView1.RowUpdating += new GridViewUpdateEventHandler(GridView1_RowUpdating);
GridView1.DataKeyNames = new string[] { "id" };
GridView1.RowEditing += new GridViewEditEventHandler(GridView1_RowEditing);
}
else
Response.Write("fkj");
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
string cls = ((TextBox)(row.Cells[2].Controls[0])).Text;
string nam = ((TextBox)(row.Cells[3].Controls[0])).Text;
foreach (DictionaryEntry entry in e.NewValues)
{
e.NewValues[entry.Key] = Server.HtmlEncode(entry.Value.ToString());
}
com = new SqlCommand("Update tblExpt set name='" + nam + "',class='" + cls + "' where id='" + id + "'", con);
da = new SqlDataAdapter(com);
GridView1.EditIndex = -1;
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
In the above code when i try to access e.new values index out of range exception is thrown.
The table being accessed contains 3 fields id, class, name
Please help to solve the problem.
Read this blog post I wrote on extracting data from gridview (and other data controls). Also, in .net 4.0 if you use 2 way binding (<# Bind("") #>) e.NewValues will be populated.
More info here: http://weblogs.asp.net/davidfowler/archive/2008/12/12/getting-your-data-out-of-the-data-controls.aspx
The exception you get is because row.Cells[0].Controls[0] is a DataControlLinkButton and not a TextBox. Since I donĀ“t know the control layout of your grid you could search for your textbox instead.
Instead of:
int id = int.Parse(((TextBox)(row.Cells[0].Controls[0])).Text);
do something like the code below if there is only one TextBox per row:
TextBox box = (TextBox)row.Cells[0].Controls.OfType<TextBox>().First();
int id = int.Parse( box.Text );
If you have nested html and hierarchies check out this SO question for nested searching of controls

Resources