System.ArgumentOutOfRangeException When Handling Button Click - asp.net

I used a button field in a gridview. When I press button, which has index greater than 5, I received this exception:
System.ArgumentOutOfRangeException: 'Index was out of range. Must be
non-negative and less than the size of the collection.'
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "btn")
{
int crow;
crow = Convert.ToInt32(e.CommandArgument.ToString());
string v = GridView1.Rows[crow].Cells[1].Text;
int a = Int32.Parse(v);
string b = "true";
SqlConnection con = new SqlConnection("Data Source=DESKTOP-LITEG8T;Initial Catalog=UserDb;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE Table_1 SET Status ='"+b+"' WHERE Id ='"+ a+"'", con);
cmd.ExecuteNonQuery();
con.Close();
v = "";
}
}
}

public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "btn")
{
int crow;
crow = Convert.ToInt32(e.CommandArgument.ToString());
try
{
string v = GridView1.Rows[crow].Cells[1].Text;
Application["id"] = v;
v = "";
}
catch (ArgumentOutOfRangeException)
{
}
finally
{
string a = Application["id"].ToString();
Label1.Text = a.ToString();
string b = "true";
SqlConnection con = new SqlConnection("Data Source=DESKTOP-LITEG8T;Initial Catalog=UserDb;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE Table_1 SET Status ='" + b + "' WHERE Id ='" + a + "'", con);
cmd.ExecuteNonQuery();
con.Close();
Application["id"] = "";
a = "";
}
}
}
}

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

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.

dropdownlist index changed value

I have a problem when I change dropdownlist1 item, The changed item not being accessed on the event of DropDownList1_SelectedIndexChanged.
Here is my code...
namespace My_News.Views.Shared
{
public partial class Master : System.Web.UI.MasterPage
{
SqlDataReader dr;
string user_id = "";
protected void Page_Load(object sender, EventArgs e)
{
/* user login information */
if (Session["status"] != null)
{
Button1.Text = "Logout";
Button2.Visible = true; ;
Button2.Text = Session["name"] as string + "'s Profile";
Button3.Enabled = true;
DropDownList1.Enabled = true;
user_id = Session["reg_id"] as string;
DropDownList1.Items.Clear();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection_String"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT DISTINCT[news_category] from [news_profile] WHERE [user_id]='" + user_id + "'";
cmd.Connection = connection;
connection.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr[0].ToString());
}
connection.Close();
}
}
}
else
{
Button1.Text = "Login";
Button2.Visible = false;
Button3.Enabled = false;
DropDownList1.Enabled = false;
Session.Clear();
}
}
Dropdownnlist index change event...
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Session["news_category"] = DropDownList1.Text;
Session["reload"] = "yes";
Session.Timeout = 10;
Response.Redirect("Default.aspx");
}
}
}
Please help me.
You need to modify your code like this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindDDL();
}
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
string s = ddl.Text;
}
public void bindDDL()
{
DataTable dt = new DataTable("Drop");
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "ABCD");
dt.Rows.Add(2, "EFGH");
ddl.DataSource = dt;
ddl.DataValueField = "ID";
ddl.DataTextField = "Name";
ddl.DataBind();
}

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.

in this code error is showing "Type or namespace definantion,end of file expected"

Type or namespace definantion,end of file expected
public partial class contact : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
if (TextBox1.Text == "")
{
/* Label2.Text = "name is compulasry";*/
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('name is compulasry');", true);
}
else
{
SqlConnection con = new SqlConnection(#"Data Source=SYSTEM2\SQLEXPRESS;Initial Catalog=amresh;Integrated Security=True");
SqlCommand cmd;
con.Open();
cmd = new SqlCommand("insert into Deatil values('"+ TextBox1.Text +"')", con);
cmd.ExecuteNonQuery();
ClearInputs(Page.Controls);
con.Close();
}
void ClearInputs(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = string.Empty;
ClearInputs(ctrl.Controls);
}
}
}
}
You missed to close Button1_Click1. You're missing a }
protected void Button1_Click1(object sender, EventArgs e)
{
if (TextBox1.Text == "")
{
/* Label2.Text = "name is compulasry";*/
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('name is compulasry');", true);
}
else
{
SqlConnection con = new SqlConnection(#"Data Source=SYSTEM2\SQLEXPRESS;Initial Catalog=amresh;Integrated Security=True");
SqlCommand cmd;
con.Open();
cmd = new SqlCommand("insert into Deatil values('"+ TextBox1.Text +"')", con);
cmd.ExecuteNonQuery();
ClearInputs(Page.Controls);
con.Close();
}
} // <-- This is missed
And you need to remove an extra } at the end
void ClearInputs(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = string.Empty;
ClearInputs(ctrl.Controls);
}
}
} // <-- Remove this

Resources