Object reference not set to an instance of an object while clicking on submit button - asp.net

I have created a webpage in asp.net
on right hand side I have an ListBox which binds data from database when page loads, Its code at Default.aspx is as below
<asp:ListBox ID="ListOfSql" runat="server"
SelectionMode="Single" DataTextField="sql_name" DataValueField="sql_text"
style="margin-left: 0px; width:auto; height:300px" EnableViewState="true">
</asp:ListBox>
and at default.aspx.cs page its code is
private void loadSqlList()
{
if (!IsPostBack)
{
conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
string preSql = "select sql_name, sql_text from cn_sql_log order by sql_name";
OracleDataAdapter da = new OracleDataAdapter(preSql, conn);
da.Fill(ds);
ListOfSql.DataSource = ds;
ListOfSql.DataTextField = "Sql_Name";
ListOfSql.DataValueField = "sql_Text";
ListOfSql.DataBind();
ListOfSql.SelectedIndex = 0;
conn.Close();
}
}
I am calling loadSqlList() on page_load so that I can get list from database in ListBox.
Now I have an submit button
<asp:Button ID="btnPreSqlExe" runat="server" Text="Sumbit"
onclick="btnPreSqlExe_Click">
</asp:Button>
on default.aspx.cs page submit button's code is
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
txtQuery.Text = ListOfSql.SelectedItem.Text.ToString();
}
Now when I want that on clicking on submit button then text of selected item should appear in textbox which is at left hand side
when I do so I am getting an error page
complete code of default.aspx.cs page is as below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Windows.Forms;
using System.IO;
using System.Threading;
public partial class _Default : System.Web.UI.Page
{
System.Data.OracleClient.OracleConnection conn = new OracleConnection("Data Source = orcl; user id=*****;password = *****; unicode = true;");
//OracleConnection conn = new OracleConnection("Data Source=orcl;Persist Security Info=True;User ID=system;password = ravi_123;Unicode=True");
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
loadSqlList();
lblLastRefresh.Text = DateTime.Now.ToShortTimeString();
lblDate.Text = DateTime.Now.ToShortDateString();
Response.Cache.SetAllowResponseInBrowserHistory(false);
//============================================= Checking user logged in or not ===================================
//if (Session["txtUserName"] == null)
//{
// Response.Write("<Script Language ='JavaScript'> alert('Session Expired, please login again')</script>");
// conn.Close();
// Response.Redirect("login.aspx");
//}
//============================================= Checking user logged in or not (END) ===================================
//=====================User Ip Tracer =======================
string UserIp = Request.ServerVariables["http_x_forwarded_for"];
string UserHost = Request.ServerVariables["http_X_forwarded_for"];
string userMacAdd = Request.ServerVariables["http_x_forwarde_for"];
if (string.IsNullOrEmpty(UserIp))
{
UserIp = Request.ServerVariables["Remote_ADDR"];
UserHost = System.Net.Dns.GetHostName();
}
LblLoc.Text = UserIp;
LblHostName.Text = UserHost;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Response.AddHeader("Pragma", "no-cache");
//=====================User Ip Tracer code end =======================
if (!IsPostBack)
{
}
}
protected void onclick_logout(object sender, EventArgs e)
{
conn.Close();
Session.Clear();
Response.Redirect("login.aspx");
}
protected void exportToExcel_Click(object sender, EventArgs e)
{
try
{
conn.Open();
string sql;
sql = txtQuery.Text.ToString();
OracleDataAdapter da = new OracleDataAdapter(sql, conn);
//================ User Details Data Insertion in DataBase Ends here ===============
da.Fill(dt);
ExportTableData(dt);
Response.Write("<Script>alert('Ip Locked in DB')</Script>");
}
catch (Exception ex)
{
lblError.Text = ex.Message.ToString();
}
}
protected void btnClear_clik(object sender, EventArgs e)
{
txtQuery.Text = string.Empty;
}
private void ExportTableData(DataTable dtdata)
{
string attach = "attachment;filename="+ListOfSql.SelectedItem.Text.ToString()+".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attach);
Response.ContentType = "application/ms-excel";
if (dtdata != null)
{
foreach (DataColumn dc in dtdata.Columns)
{
Response.Write(dc.ColumnName + "\t");
}
Response.Write(System.Environment.NewLine);
foreach (DataRow dr in dtdata.Rows)
{
for (int i = 0; i < dtdata.Columns.Count; i++)
{
Response.Write(dr[i].ToString() + "\t");
}
Response.Write("\n");
}
Response.End();
}
}
// References for this page
// http://forums.asp.net/t/1768549.aspx
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
txtQuery.Text = ListOfSql.SelectedItem.Text.ToString();
}
private void loadSqlList()
{
if (!IsPostBack)
{
conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
string preSql = "select sql_name, sql_text from cn_sql_log order by sql_name";
OracleDataAdapter da = new OracleDataAdapter(preSql, conn);
da.Fill(ds);
ListOfSql.DataSource = ds;
ListOfSql.DataTextField = "Sql_Name";
ListOfSql.DataValueField = "sql_Text";
ListOfSql.DataBind();
ListOfSql.SelectedIndex = 0;
conn.Close();
}
}
}

If a selection isn't made then ListOfSql.SelectedItem will be null, and therefore calling .Text on that will result in your error.
Try changing your code to something like this:
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
if(ListOfSql.SelectedItem != null)
{
txtQuery.Text = ListOfSql.SelectedItem.Text.ToString();
}
}

Related

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";
}

asp.net grid view edit and delete records

i am trying to use a grid view to display items from the database i also want to edit and delete these records then in the grid view, i am using the sample code on asp.net snippets
http://aspsnippets.com/Articles/Simple-Insert-Select-Edit-Update-and-Delete-in-ASPNet-GridView-control.aspx
it says that The name 'GetData' does not exist in the current context
using System;
using System.Collections.Generic;
using System.Configuration;
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 Default10 : System.Web.UI.Page
{
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
comm = new SqlCommand("select EmployeeID,Name,Password" +
" from Employee");
GridView1.DataSource = GetData(comm);
GridView1.DataBind();
}
protected void EditEmployee(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void UpdateEmployee(object sender, GridViewUpdateEventArgs e)
{
string EmployeeID = ((Label)GridView1.Rows[e.RowIndex]
.FindControl("lblEmployeeID")).Text;
string Name = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtName")).Text;
string Password = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtPassword")).Text;
comm = new SqlCommand();
comm.CommandType = CommandType.Text;
comm.CommandText = "update Employee set Name=#Name," +
"Password=#Password where EmployeeID=#EmployeeID;" +
"select EmployeeID,Name,Password from Employee";
comm.Parameters.Add("#EmployeeID", SqlDbType.VarChar).Value = EmployeeID;
comm.Parameters.Add("#Name", SqlDbType.VarChar).Value = Name;
comm.Parameters.Add("#Password", SqlDbType.VarChar).Value = Password;
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(comm);
GridView1.DataBind();
}
protected void DeleteEmployee(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
comm = new SqlCommand();
comm.CommandType = CommandType.Text;
comm.CommandText = "delete from Employee where " +
"EmployeeID=#EmployeeID;" +
"select EmployeeID,Name,Password from Employee";
comm.Parameters.Add("#EmployeeID", SqlDbType.VarChar).Value
= lnkRemove.CommandArgument;
GridView1.DataSource = GetData(comm);
GridView1.DataBind();
}
}
You are using Old coding so Replace your code with my code..
using System;
using System.Collections.Generic;
using System.Configuration;
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 Default10 : System.Web.UI.Page
{
SqlCommand comm;
SqlConnection connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
connectionString.Open();
comm = new SqlCommand("select EmployeeID,Name,Password from Employee", connectionString);
DataTable dt =new DataTable();
SqlDataAdapter adp= new SqlDataAdapter(comm);
adp.Fill(dt);
connectionString.Close();
GridView1.DataSource =dt;
GridView1.DataBind();
}
protected void EditEmployee(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
//you should Write this code on Rowupdating and give command name 'update' to link button
protected void UpdateEmployee(object sender, GridViewUpdateEventArgs e)
{
//start here
string EmployeeID = ((Label)GridView1.Rows[e.RowIndex]
.FindControl("lblEmployeeID")).Text;
string Name = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtName")).Text;
string Password = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtPassword")).Text;
connectionString.Open();
comm = new SqlCommand("update Employee set Name=#Name,Password=#Password where EmployeeID=#EmployeeID", connectionString);
comm.Parameters.AddWithValue("#EmployeeID", EmployeeID);
comm.Parameters.AddWithValue("#Name", Name);
comm.Parameters.AddWithValue("#Password", Password);
comm.ExecuteNonQuery();
connectionString.Close();
GridView1.EditIndex = -1;
BindData();
//end here
}
//you should Write this code on RowDeleting and give command name 'delete' to link button
protected void DeleteEmployee(object sender, EventArgs e)
{
//stat here
string EmployeeID = ((Label)GridView1.Rows[e.RowIndex]
.FindControl("lblEmployeeID")).Text;
connectionString.Open();
comm = new SqlCommand("delete from Employee where EmployeeID=#EmployeeID", connectionString);
comm.Parameters.AddWithValue("#EmployeeID", lnkRemove);
comm.ExecuteNonQuery();
connectionString.Close();
BindData();
//end here
}
}

get value into query from edit mode in gridview

I have a simple gridview, 2 columns. The first column is a numeric value. The second column is based on a selected value from a drop down list. I have the drop down list working, but when I go to update the table, I get an error :
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
The offending line is 55
Line 53: {
Line 54: string BU = (gvSummary.Rows[e.RowIndex].FindControl("dlBU") as DropDownList).SelectedItem.Value;
Line 55: string AnnoNum = gvSummary.DataKeys[e.RowIndex].Value.ToString();
and here is the code behind for the webform:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Configuration;
namespace SHCAnnotation
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
protected void EditSummary(object sender, GridViewEditEventArgs e)
{
gvSummary.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvSummary.EditIndex = -1;
BindData();
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvSummary.EditIndex == e.Row.RowIndex)
{
DropDownList dlBU = (DropDownList)e.Row.FindControl("dlBU");
string query = "select distinct Unit from vw_KmartBU";
SqlCommand cmd = new SqlCommand(query);
dlBU.DataSource = GetData(cmd);
dlBU.DataTextField = "Unit";
dlBU.DataValueField = "Unit";
dlBU.DataBind();
//dlBU.Items.FindByValue((e.Row.FindControl("lblBU") as Label).Text).Selected = true;
}
}
protected void UpdateSummary(object sender, GridViewUpdateEventArgs e)
{
string BU = (gvSummary.Rows[e.RowIndex].FindControl("dlBU") as DropDownList).SelectedItem.Value;
string AnnoNum = gvSummary.DataKeys[e.RowIndex].Value.ToString();
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
string query = "update vw_GridviewSource set [Business Unit] = #BU where [Annotation Number] = #AnnoNum";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#BU", BU);
cmd.Parameters.AddWithValue("#AnnoNum", AnnoNum);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
private void BindData()
{
string query = "select [Annotation Number], [Business Unit] as Unit from vw_GridviewSource";
SqlCommand cmd = new SqlCommand(query);
gvSummary.DataSource = GetData(cmd);
gvSummary.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
}
What I need to do is get the value in first column "Annotation Number" and use it in the where clause of my update. So I would need update vw_GridviewSource set [Business Unit] = 'Accessories' where [Annotation Number] = '123456'
Accessories would have been the selection from the drop down list and 123456 would have been in the text box when I selected that row for editing.
Your gridview is missing DataKeyNames. It may look like:
<asp:GridView ID="gvSummary"
runat="server"
AutoGenerateColumns="False"
DataKeyNames="AnnoNum, MyOtherKey1, MyOtherKey2"
... ... ...
DataKeyNames property is an array of strings. You can find more in MSDN

How to get modified value of TextBox

This is PageLoad code
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//DropDownList Binding through bussiness logic
Bussiness_logic.DropDownList_Bind(DDL_U, "SHORT_DESC", "UNIT_CODE", "UNIT_SOURCE");
Bussiness_logic.DropDownList_Bind(DDL_Branch, "TYPE_DESC", "TYPE_CODE", "BRANCH_SOURCE");
}
if (Request.QueryString["File"] != null)
{
string fileNo = Request.QueryString["File"].ToString();
Bussiness_logic.OpenConnection();
SqlCommand com = new SqlCommand("LINK_DATA", Bussiness_logic.con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FILE", fileNo);
SqlDataReader dtr = com.ExecuteReader();
if (dtr.HasRows)
{
dtr.Read();
{
TxtFile.Text = dtr["FILE_NO"].ToString();
DDL_Branch.SelectedValue = dtr["TYPE_DESC"].ToString();
TxtSub.Text = dtr["SUBJECT"].ToString();
DDL_U.SelectedValue = dtr["SHORT_DESC"].ToString();
}
}
Bussiness_logic.CloseConnection();
Label1.Text = "";
}
}
I have get value of QueryString from another page and file my fields according to File variable fetching data from database corresponding to File data .Fields(Two Textbox and two DropDwnList) are filling correctly but when i modify data in textbox or DDL and Click on Update button then it is not updating data .
Update Button code
protected void BtnUpdate_Click(object sender, EventArgs e)
{
Bussiness_logic.OpenConnection();
SqlCommand com = new SqlCommand("UPDATE_DATA",Bussiness_logic.con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FILE_NO", TxtFile.Text);
com.Parameters.AddWithValue("#SUB",TxtSub.Text);
com.Parameters.AddWithValue("#UNIT",DDL_U.SelectedValue);
com.Parameters.AddWithValue("#BRANCH",DDL_Branch.SelectedValue);
com.ExecuteNonQuery();
Label1.Text = "Action perfomed successfully !!!";
Bussiness_logic.CloseConnection();
Bussiness_logic.Empty_Control(TxtFile, TxtSub, DDL_U, DDL_Branch);
//GridView1.Visible = false;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//DropDownList Binding through bussiness logic
Bussiness_logic.DropDownList_Bind(DDL_U, "SHORT_DESC", "UNIT_CODE", "UNIT_SOURCE");
Bussiness_logic.DropDownList_Bind(DDL_Branch, "TYPE_DESC", "TYPE_CODE", "BRANCH_SOURCE");
if (Request.QueryString["File"] != null)
{
string fileNo = Request.QueryString["File"].ToString();
Bussiness_logic.OpenConnection();
SqlCommand com = new SqlCommand("LINK_DATA", Bussiness_logic.con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FILE", fileNo);
SqlDataReader dtr = com.ExecuteReader();
if (dtr.HasRows)
{
dtr.Read();
{
TxtFile.Text = dtr["FILE_NO"].ToString();
DDL_Branch.SelectedValue = dtr["TYPE_DESC"].ToString();
TxtSub.Text = dtr["SUBJECT"].ToString();
DDL_U.SelectedValue = dtr["SHORT_DESC"].ToString();
}
}
Bussiness_logic.CloseConnection();
Label1.Text = "";
}
}
}
Put Your second if also in first if.Because when you click update button than your page load event fire first.Means your textbox value again set from textbox.So putting your second if inside first if stop setting the textbox value from database on postbask,

update cancel on gridview asp.net

I am trying to update a gridview on asp.net using a stored procedure but it always resets to the original values. What am I doing wrong?
edit: all page code added now
protected void page_PreInit(object sender, EventArgs e)
{
MembershipUser UserName;
try
{
if (User.Identity.IsAuthenticated)
{
// Set theme in preInit event
UserName = Membership.GetUser(User.Identity.Name);
Session["UserName"] = UserName;
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
//to edit grid view
protected void GridViewED_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewED.EditIndex = e.NewEditIndex;
}
protected void GridViewED_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_UpdateRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
command.Parameters.Add("#PostalAddress", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
command.Parameters.Add("#TelephoneNo", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
command.Parameters.Add("#Website", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
command.Parameters.Add("#Email", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
}
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
command.ExecuteNonQuery();
MyConnection.Close();
GridViewED.EditIndex = -1;
}
I suspect the code loading the grid is being invoked upon postback, which is causing the data to be pulled from the database when you don't want it to.
Yes - I think you want the code to only load if it is not a postback. You can use the Page.IsPostBack property for this.
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
if (!IsPostBack) {
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
}
Don't bind your data in the Page_Load event. Create a separate method that does it, then in the Page Load, if !IsPostback, call it.
The reason to perform the databinding is it's own method is because you'll need to call it if you're paging through the dataset, deleting, updating, etc, after you perform the task. A call to a method is better than many instances of the same, repetitive, databinding code.

Resources