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.
Related
This is my one tag:
<asp:Button ID="button" runat="server" Text="ShowOrder" onclick="newTab" />
This is my 'aspx.cs' which will be called when button is clicked
protected void newTab(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx?id="+txtSearchCustomerByID.Value);
}
What I want is to print my sql table on loaded web tab (new page) when it gets loaded.
My stored procedure is displaying the data of my table where id is equal to "id entered by user in textbox".
Now,
protected void Page_Load(object sender, EventArgs e)
{
int id_no = int.Parse(Request.QueryString["id"]);
if (Page.IsPostBack)
{
showOrders(id_no);
}
}
Now what should I have in 'Default2.aspx' so that I will get my table by using,
public void showOrders(int id)
{
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand("showOrdersSP", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", id);
con.Open();
.......
}
}
I need to use DataTable
So simply when I clicked, I will get data table on new page
You can refer below code:
public void showOrders(int id)
{
using (SqlConnection con = new SqlConnection(strConnString))
{
DataTable dt = new DataTable();
SqlParameter[] p1 = new SqlParameter[1];
p1[0] = new SqlParameter("#id", id);
dt= getRecords_table("showOrdersSP", p1); // you will get your DataTable here
}
}
// Common Method for FillYour Tables
private DataTable getRecords_table(string spname, SqlParameter[] para)
{
string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["connName"].ConnectionString.ToString();
SqlConnection con = new SqlConnection(connectionstring);
SqlDataAdapter ad = new SqlDataAdapter(spname, con);
ad.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
ad.SelectCommand.Parameters.AddRange(para);
con.Open();
ad.Fill(dt);
con.Close();
return dt;
}
Hope it will helps you
Thanks
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();
}
}
}
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.
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
My connection string is placed in web.config as follows.
<connectionStrings>
<add name="empcon" connectionString="Persist Security Info=False;User ID=sa;Password=abc;Initial Catalog=db5pmto8pm;Data Source=SOWMYA-3BBF60D0\SOWMYA" />
</connectionStrings>
and the code of program is...
public partial class empoperations : System.Web.UI.Page
{
string constr = null;
protected void Page_Load(object sender, EventArgs e)
{
ConfigurationManager.ConnectionStrings["empcon"].ToString();
if (!this.IsPostBack)
{
fillemps();
}
}
public void fillemps()
{
dlstemps.Items.Clear();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["empcon"].ConnectionString);
con.ConnectionString = constr;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from emp";
cmd.Connection = con;
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem lt = new ListItem();
lt.Text = reader["ename"].ToString();
lt.Value = reader["empno"].ToString();
dlstemps.Items.Add(lt);
}
reader.Close();
}
catch (Exception er)
{
lblerror.Text = er.Message;
}
finally
{
con.Close();
}
i am totally new to programing....
i am able to run this application with er.message in label control as "the connection string property has not been initialized"
i need to retrieve the list of names of employees from the emp table in database into the dropdownlist and show them to the user...
can any one please fix it...
Where are you initializing your constr variable? It looks like you can leave that line out.
Also: just use using
using(SqlConnection con = new SqlConnection(
ConfigurationManager.ConnectionStrings["empcon"].ConnectionString)
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
//Rest of your code here
}
}
Side note: Don't use Select * From. Call out your columns: Select empname, empno From...
You are not assigning ConfigurationManager.ConnectionStrings["empcon"].ToString(); to string constr
protected void Page_Load(object sender, EventArgs e)
{
constr = ConfigurationManager.ConnectionStrings["empcon"].ToString();
...
will probably solve your problem for the time being.