C# ListView index and column to string - c#

I have a listview that has 2 columns and a checkbox.
What i'm doing is if the checkbox is true, I want to check the text from columns 1 and 2 and make it a string. This is what I have.
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Checked == true)
{
listView1.Items.RemoveAt(i);
string sql = "uscolumn = '" + listView1.Items[i].ToString() + "' and ukcolumn = '" + listView1.Items[i].ToString() + "'";
}
}
The above code doesn't work but i'm not sure which way to go with it, the .Check works as intended but the strings dont.
so in this example:
CheckBox|column1|Column2
True|Fruit|Apples
usColumn = "Fruit"
ulColumn = "Apples"

Here is my suggestion for you:
int i = 0;
while (i < listView1.Items.Count)
{
if (listView.Items[i].Checked)
{
string sql = "uscolumn = '" + listView1.Items[i].SubItems[0].Text + "' and ukcolumn = '" + listView1.Items[i].SubItems[1].Text + "'";
listView.Items.RemoveAt(i);
}
else
{
i++;
}
}

I think you need to use Items[i].Text rather than ToString():
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Checked == true)
{
listView1.Items.RemoveAt(i);
string sql = "uscolumn = '" + listView1.Items[i].Text + "' and ukcolumn = '" + listView1.Items[i].Text + "'";
}
}

To delete the rows safly, you can save the item name in a array and then remove them after you go through the whole list.
This assumes that you use unique names for each one, if the Name properie is not used at all you can add a Name specificly for the deletion.
List<string> toDelete = new List<int>;
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Checked == true)
{
toDelete.Add(listView1.Items[0].Name);
string sql = "uscolumn = '" + listView1.Items[i].Text + "' and ukcolumn = '" + listView1.Items[i].Text + "'";`
}
}
foreach(string name in toDelete)
listView1.ItemsRemoveByKey(name);
Another way to do it would be to remove 1 from i each time you delete.
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Checked == true)
{
string sql = "uscolumn = '" + listView1.Items[i].Text + "' and ukcolumn = '" + listView1.Items[i].Text + "'";
listView1.Items.RemoveAt(i--);
}
}

Related

Inserting Multiple selected Listbox items into the same cell in SQL table

I want to insert multiple list box items into a a cell In SQL table with a comma dividing the items. The code posted below will only add the first selected item within a listbox. Hence If you select 2 or 10 items the first one u selected will be Inserted into the table. The for loop is my problem, I need to get all the selected values.
Thanks
protected void pg_upload_Click(object sender, EventArgs e)
{
using (SqlConnection mycon = new SqlConnection(connectionstring))
{
using (SqlCommand mycmd = mycon.CreateCommand())
{
if (textbox_make.Text == string.Empty || textbox_number.Text == string.Empty)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('The Make/Model and Number must be Entered')", true);
}
else
{
string str = "";
for (int i=0; i<= listbox_software.Items.Count; i++)
{
str = listbox_software.SelectedItem.ToString();
}
mycon.Open();
mycmd.CommandText = "INSERT INTO tbl_PG (Model, PGNumber, AssetNo, Area, Owner,IPAddress, SerialNo, OSVersion, Memory, Software) " +
"Values ('" + textbox_make.Text + "' , '" + textbox_number.Text + "' , '" + textbox_asset.Text + "' , '" + drop_area.Text + "' , '" + drop_owner.Text + "' , '" + textbox_ip.Text + "' " +
", '" + textbox_serial.Text + "' , '" + textbox_os.Text + "' , '" + textbox_memory.Text + "' , '" + str + "')";
mycmd.ExecuteNonQuery();
PopulateGridView();
lblsuscessmessage.Text = "Selected Record Added";
lblerrormessage.Text = "";
textbox_make.Text = string.Empty;
textbox_number.Text = string.Empty;
textbox_asset.Text = string.Empty;
textbox_ip.Text = string.Empty;
textbox_serial.Text = string.Empty;
textbox_os.Text = string.Empty;
textbox_memory.Text = string.Empty;
}
}
}
}
Add following namespace:
using System.Linq;
Create a string array of selected items and then use string.join:
var selection = listbox_software.SelectedItems
.Cast<string>()
.ToArray();
var str = string.Join(",", selection);
I found out the answer.
// To access checkbox list item's value //
string total = "";
foreach (ListItem listItem in listbox_software.Items)
{
if (listItem.Selected)
{
total = total + "[" + listItem.Value + "][ " + " ";
}
}
string str = total.ToString();

Error - The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data

try
{
string CSVFilePathName = textBox4.Text;
for (int i = 0; i < CSVFilePathName.Length; i++)
{
if (CSVFilePathName[i] == '\\')
{
CSVFilePathName.Insert(i + 1, "\\");
}
}
if (string.IsNullOrWhiteSpace(textBox4.Text))
{
MessageBox.Show("Please Select a File");
}
else
{
int count = 0;
// your code here
// string CSVFilePathName = #"'" + textBox4.Text + "'";
string[] Lines = File.ReadAllLines(CSVFilePathName);
string[] Fields;
Fields = Lines[0].Split(new char[] { ',' });
int Cols = Fields.GetLength(0);
DataTable dt = new DataTable();
for (int i = 1; i < Lines.GetLength(0); i++)
{
Fields = Lines[i].Split(new char[] { ',' });
for (int f = 0; f < Cols; f++)
{
q = "SELECT * from questions where main_section='" + Fields[0] + "' AND secondary_section='" + Fields[1] + "' AND tert_section='" + Fields[2] + "' AND question='" + Fields[3] + "' AND difficulty='" + Fields[4] + "'";
OleDbCommand cmdn = new OleDbCommand(q, conn);
//MessageBox.Show(q);
object obj = cmdn.ExecuteScalar();
if (obj == null)
{
q = "insert into questions values('" + Fields[0] + "','" + Fields[1] + "','" + Fields[2] + "','" + Fields[3] + "' ,'" + Fields[4] + "')";
OleDbCommand cmdn1 = new OleDbCommand(q, conn);
cmdn1.ExecuteNonQuery();
}
else
{
count++;
}
//MessageBox.Show(Fields[f]);
}
}
// dataGridClients.DataSource = dt;
string msg = "Upload successful\n";
if (count > 0)
{
msg=count.ToString()+" Questions missed due to their duplicates in the database.";
}
MessageBox.Show(msg);
}
}
catch (Exception ex)
{
MessageBox.Show("Error is " + ex.ToString());
throw;
}
I am using c# winform to upload a csv file to my ms access db, but it is givig the error "The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data." What should do now?
I suggest specifying the table fields in the SQL like
INSERT INTO questions (fieldname1, fieldname2, ...) VALUES (...)
Use parameterized-values rather than writing the values directly in the string. This also allows you to specify the datatype and then the ADO.Net OLE adapter will hopefully handle it appropriately and get the long text inserted with no trouble. Go to Read / Write BLOBs ... for an example inserting BLOBS. The concept and code example are very relevant to inserting Long Text values. It demonstrates how to set up parameters for the query. In your case, use OleDbType.LongVarWChar for the Long Text fields.

Wrong Data Is Inserted in Access Database with C#

I have a small problem regarding the Access Database when it has data inserted.
I have a button that inserts data when it's clicked. Here it is the code:
string[] read = File.ReadAllLines("Harta_Distantelor.txt");
string[] orase = { "Constanta", "Varna", "Burgas", "Istambul", "Kozlu", "Samsun", "Batumi", "Sokhumi", "Soci", "Anapa", "Yalta", "Sevastopol", "Odessa" };
OleDbCommand cmd;
for (int i = 0; i < read.Length; i++)
{
int j = 0;
string[] numbers = read[i].Split(' ');
while (j < read.Length)
{
//cmd = new OleDbCommand("UPDATE Distante SET ID_Port='" + (i + 1) + "', ID_Port_Destinatie='" + (j + 1) + "', Nume_Port_Destinatie='" + orase[j] + "' WHERE Distanta='" + numbers[j] + "' ", conn);
cmd = new OleDbCommand("INSERT INTO [Distante]([ID_Port], [ID_Port_Destinatie], [Nume_Port_Destinatie], [Distanta]) VALUES ('" + (i + 1).ToString() + "', '" + (j + 1).ToString() + "', '" + orase[j] + "', '" + numbers[j] + "')", conn);
cmd.ExecuteNonQuery();
j++;
}
}
The problem is that instead of having something like ID_Port=1, ID_Port_Destinatie=1, Nume_Port_Destinatie="Constanta", ID_Port=1, ID_Port_Destinatie=2, Nume_Port_Destinatie="Varna" and so on, I get this...
https://i.stack.imgur.com/OjMQm.png
The file "Harta_Distantelor.txt" is a matrix that has the distances, so that's why I tried to split every number from a line(string[] numbers = read[i].Split(' ');). I have to mention that [Distanta] data is correctly inserted, but the rest of the data is totally randomly inserted. I tried to figure out where the problem is, but I have no clue. Where is the mistake? What should I try to do in order to have the data showed correctly?
1.) Create a table called HartaDistantelor with columns for ID_Port, ID_Port_Destinatie, and Distanta
2.) Fill the table HartaDistantelor with your matrix values. You may be able to copy and paste directly into Access
3.) Create a table called Orase with columns for ID_Port and Nume_Port
4.) Fill the table Orase with the 13 values from your array. It should look like this:
1 Constanta
2 Varna
3 Burgas
4 ...
5.) Change your code:
OleDbCommand cmd;
for (int i = 0; i < 12; i++)
{
for (int j = 0; j < 12; j++)
{
cmd = new OleDbCommand("INSERT INTO Distante (ID_Port, ID_Port_Destinatie, Nume_Port_Destinatie, Distanta) SELECT " + (i + 1).ToString() + ", " + (j + 1).ToString() + ", o.Nume_Port, h.Distanta FROM Orase o JOIN HartaDistantelor h ON h.ID_Port = o.ID_Port WHERE h.ID_Port = i AND h.ID_Port_Destinatie = j", conn);
cmd.ExecuteNonQuery();
}
}
My approach joins records from two tables using ID values that match. I don't think you made any mistake, but used a method with more complexity than was necessary.

Visual studio C# Oracle database sort Date

I am not able to find what's wrong with the following code. There is a form on which the selected start date and finish date , as well as a button transition to a new form where DataGridView populated the database , it is necessary to conclusions regarding the selected date , but that he does not want to issue ORA- 00933.No "where" all is well.
void renewOtchet()
{
dgvOtchet.Rows.Clear();
OracleCommand ocm = Oracle.DBConneciton.CreateCommand();
ocm.CommandText = "select num, date_start, date_finish, " +
"trim(name_video), price_video, " +
"trim(fam_client), " +
"trim(kind_zal) from video.allData" +
"where date_start >= ('"+ date1 + "', 'DD.MM.YYYY' ) and date_finish <= ('" + date2+ "', 'DD.MM.YYYY') ";
string[] str = new string[7];
OracleDataReader ord = ocm.ExecuteReader();
while (ord.Read())
{
for (int i = 0; i < 7; i++)
{
str[i] = ord[i].ToString();
if (i == 1 || i == 2)
{
str[i] = str[i].Remove(10);
}
}
dgvOtchet.Rows.Add(str);
}
ord.Dispose();
ord.Close();
}
You can try this.
"select num, date_start, date_finish, " +
"trim(name_video), price_video, " + "trim(fam_client), " +
"trim(kind_zal) from video.allData " +
"where date_start >= TO_DATE('"+ date1 + "', 'DD.MM.YYYY' )
and date_finish <= TO_DATE('" + date2+ "','DD.MM.YYYY') ";
string[] str = new string[7];

Cannot UPDATE to an .mdb file using C#

At first I tried this:
string set = "";
for (int i = 1; i < result.Count; i++)
{
if ((fieldtypes[i] == "System.Int32"))
{
set += fields[i] + "=" + result[i] + ", ";
}
else if (fieldtypes[i] == "System.String")
{
set += fields[i] + "='" + result[i] + "', ";
}
else if (fieldtypes[i] == "System.Boolean")
{
set += fields[i] + "=" + result[i] + ", ";
}
else if (fieldtypes[i] == "System.DateTime")
{
set += fields[i] + "='#" + System.DateTime.Now + "#', ";
}
}
set = set.Substring(0, set.Length - 2);
string sql11 = "UPDATE [Contacts] SET " + set + " WHERE pkContactID=" + cKey;
OleDbCommand myCommand11 = new OleDbCommand(sql11, myConnection);
myCommand11.ExecuteNonQuery();
Now this WORKED when I omitted the string and datetime conditions so that it only updated the int and boolean. So it has something to do with a syntax error when I try to update a field where the type is a string.
Then I heard that you have to use parameters when writing to an .mdb file, so I tried this:
string sql11 = "UPDATE [Contacts] SET ";
for (int i = 1; i < result.Count; i++)
{
sql11 += fields[i] + " = ?, ";
}
sql11 = sql11.Substring(0, sql11.Length - 2);
sql11 += " WHERE pkContactID = " + cKey;
using (myConnection)
{
using (OleDbCommand myCommand11 = new OleDbCommand(sql11, myConnection))
{
myCommand11.CommandType = CommandType.Text;
for (int j = 1; j < result.Count; j++)
{
if (fieldtypes[j] == "System.Int32")
{
myCommand11.Parameters.AddWithValue(fields[j], int.Parse(result[j]));
}
else if (fieldtypes[j] == "System.String")
{
myCommand11.Parameters.AddWithValue(fields[j], result[j]);
}
else if (fieldtypes[j] == "System.Boolean")
{
myCommand11.Parameters.AddWithValue(fields[j], Boolean.Parse(result[j]));
}
else if (fieldtypes[j] == "System.DateTime")
{
myCommand11.Parameters.AddWithValue(fields[j], DateTime.Now);
}
}
Console.WriteLine(sql11);
myCommand11.ExecuteNonQuery();
}
}
}
Which did not work either. I don't think the ?'s are being replaced properly.
Anyway, please help me fix it so that I can update properly.
Instead of having to mess around with the UPDATE query string for Access, which is easily prone to syntax errors, I just created a DataTable object and SELECTed the row I wanted to UPDATE. I then updated the table via an array of the elements that I wanted to change, then updated the table back to the server using an adapter. This worked out well without me worrying about the syntax! :)
Cheers

Categories

Resources