I have a gridview that has and auto- generated delete button. The grid has one datakeyname and for some reason it I am getting this error : Message: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
I have looked at many tutorials and examples. This code should work right?
protected void grdBins_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int rec_id = int.Parse(grdBins.DataKeys[e.RowIndex].Value.ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete from t_run_schedule_lots " +
"where rec_id = #id";
cmd.Parameters.Add("#id", SqlDbType.Int).Value = rec_id ;
cmd.CommandType = CommandType.Text;
cmd.Connection = this.sqlConnection1;
this.sqlConnection1.Open();
//execute insert statement
cmd.ExecuteNonQuery();
this.sqlConnection1.Close();
//re-populate grid */
fill_grid();
grdBins.EditIndex = -1;
grdBins.DataBind();
// this bit was just to see if I was capturing the ID field properly.
lblBins.Visible = true;
lblBins.Text = rec_id.ToString();
}
If anyone knows a good example in C# that would make this work it would be greatly appreciated.
I might be misunderstanding your question but according to here the EditIndex property is zero-based so you can't set it to -1. Setting it to that value will throw an ArgumentOutOfRangeException.
Here is what I did to get it working:
GridViewRow row = (GridViewRow)grdBins.Rows[e.RowIndex];
Label id = (Label)row.FindControl("Label9");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete from t_run_schedule_lots " +
"where rec_id = #id";
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32(id.Text) ;
Although I don't know why the RowIndex option would not work. Anyway it is working now.
Sounds like you don't have the DataKeyNames="rec_id" in the gridview aspx set?
cant get to datakeys if you haven't let the page know what they are
this is a refactored version of your code.
protected void grdBins_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int rec_id = int.Parse(grdBins.DataKeys[e.RowIndex].Value.ToString());
using (SqlConnection conn = new SqlConnection(connectionString)){
conn.Open();
string cmdText = #"delete from t_run_schedule_lots
where rec_id = #id";
using (SqlCommand cmd = new SqlCommand(cmdText, conn)){
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#id", rec_id);
cmd.ExecuteNonQuery();
}
}
grd.EditIndex = -1;
fill_grid();
grdBins.DataBind();
}
Related
I have found many posts on here which are relating to my issue however I am struggling to find out what exactly I need to change to solve my problem of updating an MS Access database from a C# application. So I apologize if people feel this post is too similar to others. Here is my update code:
private void button1_Click(object sender, EventArgs e)
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ts\Documents\testDB.accdb");
using (OleDbConnection conn = new OleDbConnection (ConnString))
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "UPDATE [Table4] SET [EmpName] = ?, [Age] = ?, [Mobile] = ? WHERE [ID] = ?";
cmd.Parameters.AddWithValue("#ID", OleDbType.VarChar).Value = idtextBox1.Text;
cmd.Parameters.AddWithValue("#EmpName", OleDbType.VarChar).Value = nametextBox2.Text;
cmd.Parameters.AddWithValue("#Age", OleDbType.VarChar).Value = agetextBox3.Text;
cmd.Parameters.AddWithValue("#Mobile", OleDbType.VarChar).Value = mobiletextBox4.Text;
cmd.Connection = conn;
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
conn.Close();
Form1_Load(sender, e);
MessageBox.Show("record updated ");
}
}
For OleDb the order of parameters is of paramount importance. The reason your update will not work, is that you are supplying the ID parameter first, whereas in your SQL it is last (comes in the WHERE clause). Move this parameter to the end and it should work.
The revised code should be something like this:
private void button1_Click(object sender, EventArgs e)
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ts\Documents\testDB.accdb");
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "UPDATE [Table4] SET [EmpName] = ?, [Age] = ?, [Mobile] = ? WHERE [ID] = ?";
cmd.Parameters.AddWithValue("#EmpName", OleDbType.VarChar).Value = nametextBox2.Text;
cmd.Parameters.AddWithValue("#Age", OleDbType.VarChar).Value = agetextBox3.Text;
cmd.Parameters.AddWithValue("#Mobile", OleDbType.VarChar).Value = mobiletextBox4.Text;
cmd.Parameters.AddWithValue("#ID", OleDbType.VarChar).Value = idtextBox1.Text;
cmd.Connection = conn;
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
}
}
Form1_Load(sender, e);
MessageBox.Show("record updated ");
}
I have made a couple of other minor changes, most importantly moving the Form1_Load and the MessageBox outside of the using block. In general you should keep code within using blocks to a minimum, so that the resources can be freed as soon as possible. I also removed the Close(). The OleDbConnection's destructor automatically calls Close(), so there is no specific need to call it yourself.
One other thing might be wrong. You have the ID as a varchar. Are you sure about this? It would be more usual if it were an integer. In which case, you would need to parse the idTextBox1.Text to an integer with int.Parse(), or safer with int.TryParse(), and change the parameter type as well.
I have this situation: in DataEntryForm I have a dropdownlist, where user selects a letter number, and according to that inserts other related data.
I plan to change letter's status in other table by choosing in dropdownlist automatically.
I am using this code:
SqlParameter answertoparam = new SqlParameter("answerto", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID ='2' where income_number=('" + ansTo + "' )";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
comm.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
comm.ExecuteNonQuery();
Unfortunately, the result is nothing.
Server is not giving error, and it simply refreshes the page that is it.
In your posted code, you are passing the SqlParameter as well as passing the value as raw data. Do either of one and preferably pass it as SqlParameter like
SqlParameter answertoparam = new SqlParameter("answertoparam", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID = '2' where income_number = #answertoparam";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
findincomelett.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
Moreover, you have two SqlCommand object in place and calling two ExecuteNonQuery() on them. correct that ... see below
SqlCommand findincomelett = new SqlCommand(commandText, conn); --1
comm.Parameters.Add(answertoparam); --2
conn.Open();
findincomelett.ExecuteNonQuery(); --1
comm.ExecuteNonQuery(); --2
As far as I understand, the issue is that the correct IncomeLetters.docState_ID is not updated to '2'.
You may want to debug and see what value you are getting in :
string ansTo = ddlAnswerTo.SelectedItem.Value;
The record in the database that you are expecting to be updated may not have the record that satisfies the where clause 'income_number = #answertoparam'
I would like to bring you here full code of the page.
Idea is: I have page for enrollment. I am passing data to DB through stored procedure (DataInserter).
Problem is here: during enrollment, user selects from dropdownlist number of the letter he would like to answer to, and in the end, the status of the letter on other table of DB (IncomeLetters.tbl), would change from "pending"('1') to "issued" ('2').
I guess, I could clear my point to you and thank you for your support!
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MaktubhoConnectionString2"].ConnectionString);
using (SqlCommand comm = new SqlCommand("DataInserter", conn))
{
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = conn;
SqlParameter employeeparam = new SqlParameter("EmployeeSentIndex", int.Parse(ddlemployee.SelectedItem.Value));
SqlParameter doctypeparam = new SqlParameter("doctype_ID", int.Parse(ddldoctype.SelectedItem.Value));
SqlParameter doccharparam = new SqlParameter("docchar_ID", int.Parse(ddldocchar.SelectedItem.Value));
SqlParameter authorityparam = new SqlParameter("authority", txtauthority.Text);
SqlParameter subjectparam = new SqlParameter("subject", txtsubject.Text);
DateTime dt = DateTime.Now;
string todasdate = dt.ToString("d", CultureInfo.CreateSpecificCulture("de-DE"));
SqlParameter entrydateparam = new SqlParameter("entrydate", todasdate);
string Pathname = "UploadImages/" + Path.GetFileName(FileUpload1.PostedFile.FileName);
SqlParameter imagepathparam = new SqlParameter("image_path", Pathname);
SqlParameter loginparam = new SqlParameter("login", "jsomon");
comm.Parameters.Add(employeeparam);
comm.Parameters.Add(doctypeparam);
comm.Parameters.Add(doccharparam);
comm.Parameters.Add(authorityparam);
comm.Parameters.Add(subjectparam);
comm.Parameters.Add(entrydateparam);
comm.Parameters.Add(imagepathparam);
comm.Parameters.Add(loginparam);
comm.Parameters.Add("#forlabel", SqlDbType.VarChar, 100);
comm.Parameters["#forlabel"].Direction = ParameterDirection.Output;
FileUpload1.SaveAs(Server.MapPath("~/UploadImages/" + FileUpload1.FileName));
string ansTo = ddlAnswerTo.SelectedItem.Value;
SqlParameter answertoparam = new SqlParameter("answertoparam", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID = '2' where income_number = #answertoparam";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
findincomelett.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
comm.ExecuteNonQuery();
lblresult.Visible = true;
Image1.Visible = true;
lblresult.Text = "Document number:";
lblnumber.Visible = true;
lblnumber.Text = (string)comm.Parameters["#forlabel"].Value; ;
conn.Close();
}
txtauthority.Text = "";
txtsubject.Text = "";
}
Please help me !!! when I select a Client in DropDownListe I want that its corresponding ID will be written in my table (cascad) in the database and not the name . Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into cascad(Client ) values('" + ddlClients.SelectedItem + "')";
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("Cascad.aspx");
}
First make sure that you've created the DDL so that it has both the ClientID and the ClientText. You can do that by specifying both the DataValueField and DataTextField before you databind the ddl.
ddlClients.DataValueField = "ClientID";
ddlClients.DataTextField = "EnterYourClientTextColNameHere";
Then when you're getting the value back from the ddl, use the SelectedValue property which will contain the ClientID associated with the ddl selection. Like this:
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
//use a sqlparameter to avoid the possibility of sql injection
SqlParameter p = new SqlParameter("p1", ddlClients.SelectedValue);
cmd.Parameters.Add(p);
cmd.CommandText = "insert into cascad(Client) values(#p1)";
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("Cascad.aspx");
}
Note that i swapped in a sqlparameter rather than concatenating the ddls value directly into the sql statement so as to avoid the possibility of sql injection.
I create a web form that contains: Dropdownlist, texbox and rename button.
The general idea is that Dropdownlist contains list of column names of one table in my database.
Then the user select one of these names and enter the new name in the textbox. After that, he click the rename button. The result is rename the selected column in my database.
My code is work well. And it is give exact result.
see my code:
protected void Button1_Click(object sender, EventArgs e)
{
string conString = #"Data Source=FATTO-TOSH\SQLEXPRESS;Initial Catalog=Positions;Integrated Security=True";
if (DropDownList1.SelectedIndex == 0)
using (var con = new SqlConnection(conString))
{
var cmd = new SqlCommand("sys.sp_rename", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#objname", "PositionsReq.skill1")
.SqlDbType = SqlDbType.NVarChar;
cmd.Parameters.AddWithValue("#newname", name.Text)
.SqlDbType = SqlDbType.NVarChar;
cmd.ExecuteNonQuery();
}
if (DropDownList1.SelectedIndex == 1)
using (var con = new SqlConnection(conString))
{
var cmd = new SqlCommand("sys.sp_rename", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#objname", "PositionsReq.skill2")
.SqlDbType = SqlDbType.NVarChar;
cmd.Parameters.AddWithValue("#newname", name.Text)
.SqlDbType = SqlDbType.NVarChar;
cmd.ExecuteNonQuery();
}
if (DropDownList1.SelectedIndex == 2)
using (var con = new SqlConnection(conString))
{
var cmd = new SqlCommand("sys.sp_rename", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#objname", "PositionsReq.skill3")
.SqlDbType = SqlDbType.NVarChar;
cmd.Parameters.AddWithValue("#newname", name.Text)
.SqlDbType = SqlDbType.NVarChar;
cmd.ExecuteNonQuery();
}
}
My question is:
The modification achieved only one time (regard to one column) because when I change the name from skill1 to Sk for example. May in other time, the user want to modify Sk to other name. the code doesn't work because it is initialize as column name is skill1 only. do you have an idea how to generalize the code to work whatever the name of the column?
thank you
Instead of using DropDownList1.SelectedIndex why don't you have the name of the column you want it to be changed to listed in the DropDownList1 and then use DropDownList1.SelectedValue like so:
protected void Button1_Click(object sender, EventArgs e)
{
string conString = #"Data Source=FATTO-TOSH\SQLEXPRESS;Initial Catalog=Positions;Integrated Security=True";
using (var con = new SqlConnection(conString))
{
var cmd = new SqlCommand("sys.sp_rename", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#objname", DropDownList1.SelectedValue)
.SqlDbType = SqlDbType.NVarChar;
cmd.Parameters.AddWithValue("#newname", name.Text)
.SqlDbType = SqlDbType.NVarChar;
cmd.ExecuteNonQuery();
}
}
MSDN
Make sure you toss in some null checking on the SelectedValue before you actually execute any commands.
What is wrong with this code? I want to catch the last value from SQL row and display it in a TextBox. Kindly help me.
private void textBox2_Leave(object sender, EventArgs e)
{
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select last(remain) from item_new_customer where cust=" + textBox2.Text + "";
float h = (float)cmd.ExecuteScalar();
textBox20.Text = h.ToString();
}
cmd.CommandText = "select max(remain) from item_new_customer where cust='" + textBox2.Text + "'";
You are open for SQL-Injection, use parameters to avoid it.
To answer your actual question, i assume that you want this column: remain. But you want the value of the last inserted record. Since you haven't mentioned the column to detect the order of insertion, i use the primary key column (not recommended):
string sql = "SELECT TOP 1 remain FROM dbo.tablename WHERE cust=#cust ORDER BY id DESC";
using(var con = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#cust", textBox2.Text);
con.Open();
double h = (double)cmd.ExecuteScalar();
textBox20.Text = h.ToString();
}
You're missing a single quote after the textBox2.Text:
private void textBox2_Leave(object sender, EventArgs e)
{
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"select max(remain) from item_new_customer where cust=" + textBox2.Text + "'";
//Missing tick here ^
float h = (float)cmd.ExecuteScalar();
textBox20.Text = h.ToString();
}
In addition, your code is an open invitation for SQL injection.
Thanks very much for all
My final right code is:
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select top 1(remain) from item_new_customer where cust='"+textBox2.Text+"' order by id desc";
int h = (int)cmd.ExecuteScalar();
textBox20.Text = h.ToString();
What I would just do is put all of the SQL row values into a listbox and then take the text of the last item in the textbox and put that into a textbox. Keep the listbox hidden
private System.Windows.Forms.ListBox listBox1;
static SqlConnection connection = new SqlConnection(#"Data Source=hostname;Initial Catalog=database_name;Integrated Security=False;User ID=user;Password=123456;");
SqlDataAdapter adapter = new SqlDataAdapter("select * from table_name", connection);
DataTable table = new DataTable();
adapter.Fill(table);
foreach (DataRow row in table.Rows)
{
listBox1.Items.Add(row["row_name"].ToString());
}
textBox20.Text = listBox1.Items[listBox1.Items.Count - 1].ToString();