How to get modified value of TextBox - asp.net

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,

Related

ViewState for private string with button

I have gridview with a Rowcommand event that let's me get the column ActivityID cell value and puts it in a private string called ActivityIDString.
private string ActivityIDString; // To be used in btUpdate
protected void gwActivity_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Page") return;
GridViewRow row = ((e.CommandSource as Control).NamingContainer as GridViewRow);
string ActivityID = row.Cells[1].Text;
ActivityIDString = ActivityID;
}
This all works when the row is selected however when i press my "btUpdate" button the ActivityIDString becomes NULL.
protected void btUpdate_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("sp_tblActivityUpdate", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ActivityID", ActivityIDString);
con.Open();
cmd.ExecuteNonQuery();
BindGridviewActivity();
}
}
I understand the issue and why it becomes NULL but I don't know exactly how to solve this issue and where to use the ViewState.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["ActivityIDStringText"] = "ActivityIDString"; // <-- SHOULD I CREATE THIS?????
}
}
this method should be something like this
protected void gwActivity_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Page") return;
GridViewRow row = ((e.CommandSource as Control).NamingContainer as GridViewRow);
string ActivityID = row.Cells[1].Text;
ViewState["ActivityIDString"] = ActivityID;
}
then retrieve it in button method
protected void btUpdate_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
string ActivityIDString= Convert.ToString(ViewState["ActivityIDString"]);
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("sp_tblActivityUpdate", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ActivityID", ActivityIDString);
con.Open();
cmd.ExecuteNonQuery();
BindGridviewActivity();
}
}
You can use Session here. Whenever a row is selected add the ID in the session and retrieve the value of the session object in the btUpdate click event and then null the session .
Inside the gwActivity_RowCommand()
Session["ActivityId"] += ";ActivityId";
and inside btUpdate_Click()
if(Session["ActivityId"]!=null){
var ActivityIds = Session["ActivityId"].Split(';'); // For Mulitple Ids if Required
Session["ActivityId"] = null;
}

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

how to map a checkbox to update the database after submit.

I need to use a the session dataTable email value for the #email and the base from the dropdownlist.
protected void Page_Load(object sender, EventArgs e)
{
DropDownList1.DataSource = (DataTable)Session["dt"];
DropDownList1.DataValueField = "base";
DropDownList1.DataTextField = "base";
DropDownList1.DataBind();
}
string str;
protected void Submit_Click(object sender, EventArgs e)
{
if (CheckBox9.Checked == true)
{
str = str + CheckBox9.Text + "x";
}
}
SqlConnection con = new SqlConnection(...);
String sql = "UPDATE INQUIRY2 set Question1 = #str WHERE email = #email AND Base = #base;";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#email", Session.dt.email);
cmd.Parameters.AddWithValue("#str", str);
cmd.Parameters.AddWithValue("#base", DropDownList1.base);
}
}
Your syntax for reading the value out of Session is wrong, you cannot use Session.dt.email.
You need to read the DataTable out of Session and cast it to a DataTable, like this:
DataTable theDataTable = null;
// Verify that dt is actually in session before trying to get it
if(Session["dt"] != null)
{
theDataTable = Session["dt"] as DataTable;
}
string email;
// Verify that the data table is not null
if(theDataTable != null)
{
email = dataTable.Rows[0]["Email"].ToString();
}
Now you can use the email string value in your SQL command parameters, like this:
cmd.Parameters.AddWithValue("#email", email);
UPDATE:
You will want to wrap your drop down list binding in Page_Load with a check for IsPostBack, because as your code is posted it will bind the drop down list every time the page loads, not just the first time, thus destroying whatever selection the user made.
Instead do this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
DropDownList1.DataSource = (DataTable)Session["dt"];
DropDownList1.DataValueField = "base";
DropDownList1.DataTextField = "base";
DropDownList1.DataBind();
}
}
Now your base value in your database parameter logic should be the value the user selected.

How to make updatable GridView in ItemTemplate

I want to show Employee details in GridView. My client wants that he should be able to update the record without clicking on Edit button to update. Hence I kept everything in the ItemTemplate field of the GridView.
My Database tables are:
Emp(EmpNo, EName, Sal, DeptNo)
Dept(DeptNo, DeptName, Location)
Hence, I have written one sp to get data: EmpNo, EName, Sal, DeptName
Here, I want to show DeptName field in DropDownList. Here only I am facing the problem. DropDownList is not filling with proper DeptName value, but the first field.
My code-behind is like below:
public partial class GvwEmployee : System.Web.UI.Page
{
SqlConnection objConn = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["STERIAConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = EmployeeList;
GridView1.DataBind();
}
}
private List<Employee> EmployeeList
{
get{
List<Employee> employeeList = new List<Employee>();
SqlCommand objCmd = new SqlCommand("usp_GetEmpDetails", objConn);
objCmd.CommandType = CommandType.StoredProcedure;
objConn.Open();
SqlDataReader objDR = objCmd.ExecuteReader();
while (objDR.Read())
{
Employee employee = new Employee();
employee.EmpNo = Convert.ToInt32(objDR["EmpNo"]);
employee.EName = Convert.ToString(objDR["EName"]);
employee.Salary = Convert.ToDouble(objDR["Salary"]);
employee.DeptNo = Convert.ToInt32(objDR["DeptNo"]);
employee.DeptName = Convert.ToString(objDR["DeptName"]);
employeeList.Add(employee);
}
objDR.Close();
objConn.Close();
return employeeList;
}
}
private List<Department> DeptList
{
get
{
List<Department> deptList = new List<Department>();
SqlCommand objCmd = new SqlCommand("usp_GetDeptDetails", objConn);
objCmd.CommandType = CommandType.StoredProcedure;
objConn.Open();
SqlDataReader objDR = objCmd.ExecuteReader();
while (objDR.Read())
{
Department dept = new Department();
dept.DeptNo = Convert.ToInt32(objDR["DEPTNO"]);
dept.DName = Convert.ToString(objDR["DNAME"]);
dept.Location = Convert.ToString(objDR["Location"]);
deptList.Add(dept);
}
objDR.Close();
objConn.Close();
return deptList;
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlDeptName = e.Row.FindControl("ddlDeptName") as DropDownList;
if (ddlDeptName != null)
{
ddlDeptName.DataSource = DeptList;
ddlDeptName.DataBind();
ddlDeptName.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
}
}
}
Can anyone please tell where is the problem, why DeptName DropDownList is not filling with its proper values?
Try this way
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var index = Convert.ToInt32(e.RowIndex.ToString());
GridViewRow row = GridView1.Rows[index];
var ddlDeptName = row.FindControl("ddlDeptName") as ddlDeptName;
if (ddlDeptName != null)
{
ddlDeptName.DataSource = DeptList;
ddlDeptName.DataTextField = "DName";
ddlDeptName.DataValueField = "DeptNo";
ddlDeptName.DataBind();
var item = new ListItem("Select Department", "");
ddlDeptName.Items.Insert(0, item);
}
}
}
I got the solution like below:
In the GridView1_RowDataBound event method, I have written the following line of code to map DropDownList with the Data got from Backend.
//ddlDeptName.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
Now, I have replaced the above line with the following line of code, and hence the problem was solved:
ddlDeptName.SelectedValue = ((Employee)e.Row.DataItem).DeptNo.ToString();
and this has solved my problem.

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