ViewState for private string with button - asp.net

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

Related

Gridview doesn't refresh after deleting a row

I have a GridView in an UpdatePanel.
When I add a row, it gets updated right away. The problem is that, when I delete a row, it doesn't update the GridView.
What can be done?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["EventId"] != null)
{
ExtractEventData();
GridView1.DataSourceID = "SqlDataSource1";
}
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string CS =
ConfigurationManager.ConnectionStrings["ss"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spInsertComment", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Comment", txtComment.Text);
cmd.Parameters.AddWithValue("#Eventid", lblEventId.Text);
cmd.Parameters.AddWithValue("#UserId", Session["UserId"].ToString());
cmd.ExecuteNonQuery();
txtComment.Text = "";
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int id = Int32.Parse(e.CommandArgument.ToString());
string CS = ConfigurationManager.ConnectionStrings["ss"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand(
"Delete from tblEventComments WHERE CommentId = #CommentId", con);
cmd.Parameters.AddWithValue("#CommentId", id);
cmd.ExecuteNonQuery();
GridView1.DataSourceID = "";
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
}
}
I have also tried removing the datasource1 connection from GridView and then re-assigned it. Still it doesn't seem to work, the way I need it to.
I don't think you will need the GridView markup here, however you can ask for it if necessary.
According to this post, you should delete the row using GridView.DeleteRow method.

keep dataTable present through page navigating aspx.net

i have data Table which is dynamically created and is bind to grid View and the page have a button which is redirecting user on another page when is clicked. That's page one.Now when user is redirected on page 2, and if he want to get back on page 1, I want to be present data Table when page load.Some example code how to do that?
page1
protected void Page_Load(object sender, EventArgs e)
{
dtCurrentTable = (DataTable)ViewState["Markici"];
GridView2.DataSource = dtCurrentTable();
GridView2.DataBind();
}
public void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Page2.aspx");
}
//method for insert dataTable in database
public void Button2_Click(object sender, EventArgs e)
{
dtCurrentTable = (DataTable)ViewState["Markici"];
Session["Markici"] = dtCurrentTable;
dtCurrentTable = (DataTable)Session["Markici"];
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
SqlCommand cmd = new SqlCommand("InsertMarkica",conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "InsertMarkica";
foreach (DataRow dr in dtCurrentTable.Rows)
{
cmd.Parameters.Clear();
//SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#FirmaID", dr["FirmaID"]);
cmd.Parameters.AddWithValue("#Godina", dr["Godina"]);
cmd.Parameters.AddWithValue("#Kasa", dr["KasaID"]);
cmd.Parameters.AddWithValue("#Masa", dr["Masa"]);
cmd.Parameters.AddWithValue("#MarkicaID", dr["MarkicaID"]);
cmd.Parameters.AddWithValue("#Datum", dr["Datum"]);
cmd.Parameters.AddWithValue("#VrabotenID", dr["VrabotenID"]);
cmd.Parameters.AddWithValue("#Smena", dr["Smena"]);
cmd.Parameters.AddWithValue("#VkIznos", dr["VkIznos"]);
cmd.Parameters.AddWithValue("#VkDanok", dr["VkDanok"]);
cmd.ExecuteNonQuery();
cmd.Connection = conn;
}
page2
public void Button2_Click(object sender, EventArgs e)
{
Reponse.Redirect("Page1.aspx");
//Now when is redirected on page1, it should be present data Tale,
//needed that data Table for inserting records in database
}
You can create a session variable as follow
protected void Page_Load(object sender, EventArgs e)
{
dtCurrentTable = (DataTable)ViewState["Markici"];
Session["Markici"]=dtCurrentTable;
GridView2.DataSource = dtCurrentTable();
GridView2.DataBind();
}
Not the value of Session["Markici"] will be available in the current session on any page. You need to cast and use it as follow
dtCurrentTable = (DataTable)Session["Markici"];

ASP.NET, Code on click of a next button

The following is my code, I am doing project on online examination in that I have a module of question to display in this when I click on next button it should go to the next question but it is not going.
public partial class Student : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
int i=1;
Session["Number"] = i;
protected void Page_Load(object sender, EventArgs e)
{
Session["Number"] = i++;
Label1.Text = Session["Number"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Questions where QuestionNo = '"+Label1.Text+"'", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Label2.Text = dr["Question"].ToString();
Label3.Text = dr["Ans1"].ToString();
Label4.Text = dr["Ans2"].ToString();
Label5.Text = dr["Ans3"].ToString();
Label6.Text = dr["Ans4"].ToString();
}
con.Close();
con.Open();
SqlCommand cmd1 = new SqlCommand("Select * from Answers where QuestionNo = '" + Label1.Text + "'", con);
SqlDataReader dr1 = cmd1.ExecuteReader();
if (dr1.Read())
{
Label8.Text = dr1["Answer"].ToString();
}
con.Close();
}
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton1.Checked)
{
Label7.Text = Label3.Text;
}
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
Label7.Text = Label4.Text;
}
}
protected void RadioButton3_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton3.Checked)
{
Label7.Text = Label5.Text;
}
}
protected void RadioButton4_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton4.Checked)
{
Label7.Text = Label6.Text;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Label7.Text == Label8.Text)
{
Label9.Text = "Your Answer is correct";
}
else
Label9.Text = "Your Answer is incorrect";
}
protected void Button2_Click(object sender, EventArgs e)
{
i++;
Session["Number"] = i;
Response.Redirect("Student.aspx");
}
}
So many bad things in this code.
You should always give names to your variables properly.
Don't concatenate SQL queries because security reasons like SQL Injection
You should use Session["Number"] to select the question number rather than Label1.Text.
Use session when it was only necessary.
First thing that you are doing wrong is how you are trying to store value of i in your Session. You are overwriting it every time you get into the method and thus resulting in same question number on each button click.
Second, you should parametrized your queries.
On each button click you should retrieve the value of i from your session and then increment it and again store it in the session. like:
int i = 0;
if (Session["Number"] == null)
{
Session["Number"] = i;
}
else
{
i = Convert.ToInt32(Session["Number"]);
}
//Later To increment Session
Session["Number"] = ++i; //First increments, then assigns the value
You should also use ++i instead of i++ since that will store the value of i before increment.

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,

Using DropDown_SelectedIndexChanged to bind gridview, but paging is not working

I have a DropDownList which is having few list items. Every time I select any item, based on it I am binding a gridview, hence resulting gridview depends on my selection. Some results are exceeding the pagesize hence I need to navigate on 2nd page in GridView, however the GridView is disappeating when I am selecting 2nd page.
protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
{
string constr = ConfigurationSettings.AppSettings["ConnectionInfo"];
SqlConnection con = new SqlConnection(constr);
con.Open();
string str = string.Empty;
str = "SELECT * FROM Table1";
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataSet ds = new DataSet();
adp.Fill(ds, "myds");
BusinessKPIGrid.DataSource = ds;
BusinessKPIGrid.DataBind();
}
protected void OnGridViewPaging(object sender, GridViewPageEventArgs e)
{
//I know I need to bind the gridview here, but how ?
BusinessKPIGrid.PageIndex = e.NewPageIndex;
BusinessKPIGrid.DataBind();
}
I don't know how to bind the gridview in paging event, since I do not have any separate binding function.
there is a separate function for page event for grid view..create separate method for binding grid & call that method on pageindexchange event..
protected void BusinessKPIGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BusinessKPIGrid.PageIndex = e.NewPageIndex;
bindyourgrid();
}
try this
protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
{
string constr = ConfigurationSettings.AppSettings["ConnectionInfo"];
SqlConnection con = new SqlConnection(constr);
con.Open();
string str = string.Empty;
str = "SELECT * FROM Table1";
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataSet ds = new DataSet();
adp.Fill(ds, "myds");
ViewState["ds"]=ds;
BusinessKPIGrid.DataSource = ds;
BusinessKPIGrid.DataBind();
}
protected void OnGridViewPaging(object sender, GridViewPageEventArgs e)
{
//I know I need to bind the gridview here, but how ?
BusinessKPIGrid.PageIndex = e.NewPageIndex;
BusinessKPIGrid.DataSource = (DataSet)ViewState["ds"];
BusinessKPIGrid.DataBind();
}
From DDL_SelectedIndexChanged if you are searching some thing then use 'PageIndexChanging' and set the page size for it
protected void gvworker_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvworker.PageIndex = e.NewPageIndex;
//result got from ddl list i.e bind your data set
}

Resources