C# for loop. Index was outside the bounds - c#

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

Related

Data is not inserted into local database

I've recently started learning some databases things in .NET (C#) and I have a problem with inserting list of objects into local database. I don't know the reason but, after executing query, base is still empty and there is no error or warning, can you tell me if there is any problem with the code, or is there any other reason why it does not work properly.
I've tried to debug, but code seems to work, it passes if statement, and adds parameter's value, I've also removed thread start method and did it synchronously but still nothing.
public static void SaveData()
{
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
using (SqlConnection conn = new SqlConnection(conString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Przestoje(Urzadzenie, Czas, Data) VALUES(#nazwa, #czas, #data)", conn))
{
cmd.Parameters.AddWithValue("#nazwa", SqlDbType.NVarChar);
cmd.Parameters.AddWithValue("#czas", SqlDbType.Int);
cmd.Parameters.AddWithValue("#data", SqlDbType.NVarChar);
int count = allEncounters.Count;
for (int i = 0; i < count; i++)
{
if (i >= NextIndex)
{
cmd.Parameters["#nazwa"].Value = allEncounters[i].Name;
cmd.Parameters["#czas"].Value = allEncounters[i].timeOnTimeout * 10;
cmd.Parameters["#data"].Value = allEncounters[i].startDate.ToString();
}
}
NextIndex = count;
}
}
}).Start();
}
At some point you have to actually execute the SQL command, which you currently don't do:
cmd.ExecuteNonQuery();
If you're looking to insert one record, this would be near the end. Though it looks like you're trying to insert multiple records in a loop, so this would of course happen inside the loop. (Once per record.)
You have to execute the SqlCommand. Put this before "NextIndex = count;":
cmd.ExecuteNonQuery();
You forgot to run in using block:
cmd.ExecuteNonQuery();
You can trim that down
for (int i = NextIndex; i < allEncounters.Count; i++)
{
cmd.Parameters["#nazwa"].Value = allEncounters[i].Name;
cmd.Parameters["#czas"].Value = allEncounters[i].timeOnTimeout * 10;
cmd.Parameters["#data"].Value = allEncounters[i].startDate.ToString();
cmd.ExecuteNonQuery();
}
NextIndex = allEncounters.Count;

Get Data from Mysql Database to array in C# array out of bounds

I connect mysql database, then I get the x row. And when I try to the push the array the system got error. I dont understand this problem.
I tried this code. But I got error like array out of bonds...
int uz = b();// this func. get row number on the table
int[] userData = new int[uz];
MySqlConnection bag = new MySqlConnection(connstring);
MySqlCommand cmd = new MySqlCommand("Select readerid From readers",bag);
bag.Open();
MySqlDataReader oku = cmd.ExecuteReader();
oku.Read();
for (int i = 0; i <= uz; i++) {
userData[i] = Convert.ToInt32(oku[i]);
listBox1.Items.Add(userData[i]);
}
bag.Close();
I think you should use i < uz instead of i <= uz.
for (int i = 0; i < uz; i++)
EDIT:
Based on your comment I think you can try this:
List<int> userData = new List<int>();
MySqlConnection bag = new MySqlConnection(connstring);
MySqlCommand cmd = new MySqlCommand("Select readerid From readers",bag);
bag.Open();
MySqlDataReader oku = cmd.ExecuteReader();
while (oku.Read())
{
int current = Convert.ToInt32(oku["readerid"]);
userData.Add(current);
listBox1.Items.Add(current);
}
Dont forget to close the connections after you dont need them.
It looks like the main problem is that you believed oku[i] would give you data from the row at index i. What it really does is give you data from the column at index i for the current row. However, there were several other issues with the original code as well.
This should point you in a better direction:
var userData = new List<int>();
using (var bag = new MySqlConnection(connstring))
using (var cmd = new MySqlCommand("Select readerid From readers",bag))
{
bag.Open();
using (MySqlDataReader oku = cmd.ExecuteReader())
{
while (oku.Read())
{
userData.Add(oku[0]);
//userData.Add(oku["readerid"]); //would also work
}
}
}

Pass items from checkboxlist to SQL Server table

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());

Reading Entries From Access Database Into DataGridView Using C#

For some reason when I try to read in numbers from an Access database using this code, I just get blank entries in my data grid. I can read strings in fine. Anyone know why this may be? And yes, the actual data type for the unread entries in Access is a NUMBER.
string strProvider = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Employees.mdb";
string strSql = "SELECT * FROM tbl_employees";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataReader dr = cmd.ExecuteReader();
int columnCount = dr.FieldCount;
for (int i = 0; i < columnCount; i++)
{
dgv.Columns.Add(dr.GetName(i).ToString(), dr.GetName(i).ToString());
}
string[] rowData = new string[columnCount];
while (dr.Read())
{
for (int k = 0; k < columnCount; k++)
{
if (dr.GetFieldType(k).ToString() =="System.Int32")
{
rowData[k] = dr.GetInt32(k).ToString();
}
if (dr.GetFieldType(k).ToString() == "System.String")
{
rowData[k] = dr.GetString(k);
}
}
dgv.Rows.Add(rowData);
}
I suggest you try stepping through your code in the debugger so you can see what's happening. My first guess would be that your numeric fields aren't returned as Int32, perhaps they are floats or decimals instead.
If for some reason you can't step through it, try something like this:
if (dr.GetFieldType(k).ToString() =="System.Int32")
{
rowData[k] = dr.GetInt32(k).ToString();
}
else if (dr.GetFieldType(k).ToString() == "System.String")
{
rowData[k] = dr.GetString(k);
}
else
{
rowData[k] = dr.GetFieldType(k).ToString();
}
That will let you see what type of value is in the fields that didn't get displayed.

extracting data from data set

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();

Categories

Resources