I'm trying to take items from a checkboxlist and add them to a SQL Server table. I assumed it would be as easy as looping through each item and then inserting it into the table, but I'm getting an unhandled exception with the following code:
using (SqlConnection connection = new SqlConnection(connectionString))
{
for (int i = 0; i <= UPCList.Items.Count; i++)
{
string finalSubmit =
"INSERT INTO Boxes (BoxNumber)"
+ "VALUES #selected";
SqlCommand command = new SqlCommand(finalSubmit, connection);
command.Parameters.AddWithValue("#selected", i);
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
}
}
Edit: one of the suggestions below worked, but it's putting in the ID of the item rather than the value of the list item itself. How can I insert the value for each item in the list into the SQL table?
Put the VALUES in paranthesis:
"INSERT INTO Boxes (BoxNumber) VALUES (#selected)";
Also, i assume you have to replace
for (int i = 0; i <= UPCList.Items.Count; i++)
with
for (int i = 0; i < UPCList.Items.Count; i++)
and you might want to insert the item's text instead of the index:
command.Parameters.AddWithValue("#selected", listBox.Items[i].ToString());
Related
I'm getting the following error:
Index was outside the bounds of the array
The for loop code:
for (int i = 0; i < listEquipment.Items.Count - 1; i++)
{
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[EquipmentItems] ([RequestID], [TypeID]) VALUES (#RequestID, #TypeID)", conn);
cmd.Parameters.Add("#RequestID", SqlDbType.Int).Value = userRequest;
cmd.Parameters.Add("#TypeID", SqlDbType.Int).Value = (listEquipment.SelectedItems[i] as Equipment).equipmentID;
cmd.ExecuteNonQuery();
}
The line with the error:
cmd.Parameters.Add("#TypeID", SqlDbType.Int).Value = (listEquipment.SelectedItems[i] as Equipment).equipmentID;
Please help! I'm new to programming.
You loop all items and then access that index in listEquipment.SelectedItems[i]. But there are probably not all items selected which means that this collection is smaller and you can't access it.
So i assume that you dont want to loop all items but only the selected, so use:
for (int i = 0; i < listEquipment.SelectedItems.Count; i++)
{
}
change
for (int i = 0; i < listEquipment.Items.Count - 1; i++)
to
for (int i = 0; i < listEquipment.SelectedItems.Count; i++)
You are looking for something like this (let me expailn via comments in the code below):
//DONE: make sql readable
string sql =
#"INSERT INTO [dbo].[EquipmentItems] (
[RequestID],
[TypeID])
VALUES (
#RequestID,
#TypeID)";
// Create command once - use many (within the loop)
//DONE: wrap IDisposable into using
using (SqlCommand cmd = new SqlCommand(sql, conn)) {
// user request is the same for all the equipment
cmd.Parameters.Add("#RequestID", SqlDbType.Int).Value = userRequest;
cmd.Parameters.Add("#TypeID", SqlDbType.Int);
//DONE: foreach + OfType<> is by far more readable in the context:
// "for each selected equipment execute a query"
foreach (Equipment equipment in listEquipment.SelectedItems.OfType<Equipment>()) {
cmd.Parameters["#TypeID"].Value = equipment.equipmentID;
cmd.ExecuteNonQuery();
}
}
In my current application I have a snippet of code that allows me to select a single row in a data grid view and store all the columns information into a variable to do with what I want. I use this primarily to send information from one SQL database table to another. It's great for only sending specified cells within a row.
Here is how I do a single row:
string ID = dataGridView1.SelectedRows[0].Cells[0].Value + string.Empty;
string itemOne= dataGridView1.SelectedRows[0].Cells[1].Value + string.Empty;
string itemTwo= dataGridView1.SelectedRows[0].Cells[2].Value + string.Empty;
string itemThree= dataGridView1.SelectedRows[0].Cells[3].Value + string.Empty;
var vItemOne = itemOne;
var vItemTwo= itemTwo;
var vItemThree= itemThree;
// ETC..
However, I now want to be able to select Multiple Rows and only insert specified columns within those rows to a SQL database.
I've tried modifying the above code to work... obviously it doesn't work.
I believe I need a loop, I haven't really used loops much so I'm not sure how to make it loop, skip certain columns, then insert into database.
This is what I am currently attempting, however I seem to be messing up somewhere.
using (SqlConnection con = new SqlConnection(Connection.MTRDataBaseConn))
{
for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO dbo.[" + txtJobName.Text + "] ([Item One], [Item Two], [Item Three]) VALUES(#ItemOne,#ItemTwo,#ItemThree)";
cmd.Connection = con;
string strItemOne = this.dataGridView1.SelectedRows[i].Cells[1].Value + string.Empty;
string strItemTwo = this.dataGridView1.SelectedRows[i].Cells[2].Value + string.Empty;
string strItemThree = this.dataGridView1.SelectedRows[i].Cells[3].Value + string.Empty;
//Parameters
cmd.Parameters.AddWithValue("#ItemOne", strItemOne);
cmd.Parameters.AddWithValue("#ItemTwo", strItemTwo);
cmd.Parameters.AddWithValue("#ItemThree", strItemThree);
//execute
cmd.ExecuteNonQuery();
//close connection
con.Close();
}
}
...
While Debugging My dataGridView.SelectedRows.Count; i++ doesn't seem to be increasing and is staying at 0... I'm receiving the error when I try to return the selected row to a string. Shouldn't my selected rows still return a value?
I'm under the assumption my loop is wrong.
Can anyone help me with my issue?
Simply have to use a for each statement
string itemOne= dataGridView1.SelectedRows[0].Cells[1].Value + string.Empty;
string itemTwo= dataGridView1.SelectedRows[0].Cells[2].Value + string.Empty;
string itemThree= dataGridView1.SelectedRows[0].Cells[3].Value + string.Empty;
var vItemOne = itemOne;
var vItemTwo= itemTwo;
var vItemThree= itemThree;
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
//Insert Query Here
}
I am reading the data grid view column values and than storing those values to database the values get add to database perfectly but at the end it give me an exception I really don't why its giving me an exception at the end .The exception is Object reference not set to an instance of an object.
here is my code .
for (int rows = 0; rows < dataGridView1.Rows.Count; rows++)
{
for (int col = 0; col < dataGridView1.Rows[rows].Cells.Count; col++)
{
string value = dataGridView1.Rows[rows].Cells[col].Value.ToString();
MessageBox.Show(value);
string st3 = "INSERT INTO aprori_words(aprori) VALUES('" + value + "')";
SqlCommand cmd = new SqlCommand(st3, con);
cmd.ExecuteNonQuery();
}
}
The most probable cause is ToString(), which throws an exception if Value is null.
Convert.ToString() returns an empty string for null, so try this instead:
var value = Convert.ToString(dataGridView1.Rows[rows].Cells[col].Value);
if (!String.IsNullOrEmpty(value))
{
// call the rest of your code to save "value" to the database
}
You should also consider parameterizing your query. It'll be easier to maintain and more secure too.
var st3 = "INSERT INTO aprori_words(aprori) VALUES(#value)";
SqlCommand cmd = new SqlCommand(st3, con);
cmd.Parameters.AddWithValue("#value", value);
cmd.ExecuteNonQuery();
Respected Users,
I am extracting data using data set.
I want to put value in textbox. But value is not comming.
I have following Code
try
{
da = new SqlDataAdapter("select ID from Customer where Name='" + gvBkPendingSearch.SelectedRows[0].Cells[1].Value.ToString() + "'",con);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
txtCustomerID.Text = ds.Tables[0].Rows[0].ToString();
}
catch (Exception ex)
{
}
finally
{
}
txtCustomerID is my textbox.
It is capturing value as>>>>>System.Data.DataRow
Error is in txtCustomerID.Text = ds.Tables[0].Rows[0].ToString();
but i am not able to understand it.
Please help me.
change it like this
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
txtCustomerID.Text = ds.Tables[0].Rows[i]["ID"].ToString();
The mistake you are doing is, you are accessing this
ds.Tables[0].Rows[0].ToString();
means 0th row, the whole row!! not the column value
And the datatable row is System.Data.DataRow in .Net
You need to select the column:
txtCustomerID.Text = ds.Tables[0].Rows[i][0].ToString();
Also note that you are overwriting the value of the textbox on each iteration of the loop. So what you will end up with is the ID of the last record in this textbox.
Also your query seems vulnerable to SQL injection. Personally I would recommend you scraping the DataSets in favor of an ORM or even plain old ADO.NET:
public static IEnumerable<int> GetIds(string name)
{
using (var conn = new SqlConnection("Your connection string comes here"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "select ID from Customer where Name=#Name";
cmd.Parameters.AddWithValue("#Name", name);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return reader.GetInt32(reader.GetOrdinal("ID"));
}
}
}
}
And now you could happily use this function:
string name = gvBkPendingSearch.SelectedRows[0].Cells[1].Value.ToString();
int id = GetIds(name).FirstOrDefault();
txtCustomerID.Text = id.ToString();
i have used a checkbox list in my project .am storing all the checked items values in arraylist using code below
ArrayList services= new ArrayList();
for (int i = 0; i < chkservices.Items.Count; i++)
{
if (chkservices.Items[i].Selected == true)
{
services.Add(chkservices.Items[i].Text+',');
}
}
now the problem is when i insert data in to database instead of data in the arraylist it gets inserted as 'System.Collections.ArrayList' how can i insert all values into database in a single insert statement?
EDIT
inserting into database
con.Open();
SqlCommand cmd = new SqlCommand("insert into XXX(First_Name,Last_Name,ServicesProvided) values ('" + txtfrstname.Text + "','" + txtlastname.Text + "','" + services + "')", con);
cmd.ExecuteNonQuery();
con.Close();
or could anyone provide me a alternative for arraylist..i need to save checked items from checkboxlist and save it in database
it should be saved in database as
First_Name Last_name ServicesProvided
user1firstname user1lastname selectedvalue1,
selectedvalue2,selectedvalue3
Why not to concatenate your data using the following code:
var mydata = String.Join(',', chkservices.Items
.Where( a => a.Selected).Select( b => b.Text));
So you can add your data as a string.
EDIT:
It is a very bad habit of concatenating strings to make a query! Apart from many side effects like in your case here it is a great security breach. Try the parameterized query instead:
SqlCommand cmd = new SqlCommand(
#"insert into XXX(First_Name,Last_Name,ServicesProvided) values
(#First_Name,#Last_Name,#ServicesProvided")", con);
cmd.Parameters.AddWithValue("#ServicesProvided", mydata);
cmd.Parameters.AddWithValue("#First_Name", frstname.Text);
cmd.Parameters.AddWithValue("#Last_Name", txtlastname.Text);
cmd.ExecuteNonQuery();
mydata is the variable from my first example.
You need to get the values of the array list and send them one by one
or create a stored procedure where you send all the values to using Alexanders Galkins example (or use the a Aggregate method). Then use the split function to split up the string and insert all the record
Using INSERT INTO statement you can insert only one row at a time unless you're using sub query to select data from other table.
As you don't have the data in the database, your only option is iterate over the array and insert each value as new row.
Don't use ArrayList, you have generic list for what you need:
List<string> services = new List<string>();
for (int i = 0; i < chkservices.Items.Count; i++)
{
if (chkservices.Items[i].Selected == true)
{
services.Add(chkservices.Items[i].Text);
}
}
//...connection stuff....
strSQL = "INSERT INTO MyTable (MyField) VALUES (#val)"
using (SqlCommand command = new SqlCommand(strSQL, connection))
{
command.Parameters.AddWithValue("#val", "");
foreach (string service in services)
{
command.Parameters["#val"].Value = service;
command.ExecuteNonQuery();
}
}
How many checkbox do you have? If you just have a little checkbox, so I suggest you transform each state of them into bit mask which represent a number, then store it to database.
long bitMask = 0; // All uncheck
for (int i = 0; i < chkServices.Items.Count; ++i) {
if (chkServices.Items[i].Checked) {
bitMask |= (1 << i);
}
}
// Store bitMask to Database
In later, you can get state via bitMask again when needed.