loop through dataset from sqlitereader c# - c#

I am getting data from a database via this:
public static DataSet read_db(string sql)
{
DataSet ds = new DataSet();
try
{
SQLiteConnection m_dbConnection;
m_dbConnection = new SQLiteConnection("Data Source=movies.db;Version=3;");
m_dbConnection.Open();
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
//reader = command.ExecuteReader();
using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(command))
{
adapter.Fill(ds);
}
m_dbConnection.Close();
return ds;
}
catch (SQLiteException ex)
{
string code = ex.Message.ToString();
MessageBox.Show("Error connection to database: " + code);
return ds;
}
}
Now I am trying to loop through this dataset, and get the values from the database, was using a regular datareader from sQLite, but that wont work because it keeps the connection open until I am done reading, which means as long as my application is open.
So now I have to change all my datareaders to a way with the dataset, this was my previous datareader way:
SQLiteDataReader reader = database.read_db("select * from proxies");
while (reader.Read())
{
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(proxytable);
row.Cells[0].Value = reader["id"];
row.Cells[1].Value = reader["proxy"];
row.Cells[2].Value = reader["port"];
row.Cells[3].Value = reader["username"];
row.Cells[4].Value = reader["password"];
if (reader["dead"].ToString() == "0")
{
status = "ok";
}
else if(reader["dead"].ToString() == "2")
{
status = "not tested";
}
else
{
status = "ok";
}
row.Cells[5].Value = status;
this.proxytable.Rows.Add(row);
}
How can I change this to work with the dataset? If possible with as little change needed because I have been using this alot.

try Like this....
DataSet ds= database.read_db("select * from proxies");
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow drw in ds.Tables[0].Rows)
{
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(proxytable);
row.Cells[0].Value = drw ["id"];
row.Cells[1].Value = drw ["proxy"];
row.Cells[2].Value = drw ["port"];
row.Cells[3].Value = drw ["username"];
row.Cells[4].Value = drw ["password"];
}
}

Related

keydown Event can't add item in datagridview

When I use the scanner to scan the barcode,
the item will be add in the first row and when I scan the second barcode,
the item will no add in the datagridview but it just adds a row only.
My column in datagridview is productid, ProductName, Description, Stock, UOM, Price
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
DataGridViewRow newRow = new DataGridViewRow();
if (textBox1.Text.Length != 0)
{
conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\Database\book1.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("SELECT productid,ProductName,Description,Stock,UOM,Price from ProductTable where productId='" + textBox1.Text + "'", conn);
DataTable dt = new DataTable();
adp.Fill(dt);
foreach (DataRow item in dt.Rows)
{
int i = dataGridView1.RowCount -1;
dataGridView1.Rows.Insert(i);
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells[0].Value = item[0].ToString();
dataGridView1.Rows[i].Cells[1].Value = item[1].ToString();
dataGridView1.Rows[i].Cells[2].Value = item[2].ToString();
dataGridView1.Rows[i].Cells[3].Value = item[3].ToString();
dataGridView1.Rows[i].Cells[4].Value = item[4].ToString();
dataGridView1.Rows[i].Cells[5].Value = item[5].ToString();
}
}
}
}
Page Screenshots:
https://ibb.co/pJ0fnx7
Your approach if your productid is a unique key as it should be, will always be returning only one result, I really dont see the need of the foreach statement here. Moreover every time you open a conn to the database you should be closing it.
My approach with this in mind would be a little different this would be
Public Class clsConn
{
Public List<Data> getSomething()
var SqlConn = new SqlConnection("your connection");
try
{
SqlConn.Open();
string sqlstring = "your sql sentence";
SqlCommand SqlCmd = new SqlCommand(sqlstring, SqlConn);
SqlDataReader reader = SqlCmd.ExecuteReader();
List<Data> dataList = new List<Data>();
if (reader.Read())
{
Data data = new Data();
data.productid = reader[0].ToString(); // this is just an example
dataList.Add(data);
}
return dataList;
}
catch (Exception ex)
{
MessageBox.Show("conexion to DB failed: " + ex.Message);
throw;
}
finally
{
SqlConn.Close();
}
}
}
}
And you should have a public data class that has all the properties you need like this for example
public class Data
{
public string productid { get; set; }
}
To use it, you have to work like this
List<Data> dbData = new List<Data>();
clsConn db = new clsConn();
dbData = db.getSomething();
//I ll leave the foreach but as I said this should be only one result
foreach (var item in DBData)
{
dataGridView1.Rows.Add(item.productid);
}
Your .Insert()-call does not provide the row to insert, and you do not handle the index returned from the Rows.Add()-call.
I have edited your code a bit so that it should work now.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode != Keys.Enter) || (textBox1.Text.Length == 0))
{
return;
}
conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\Database\book1.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("SELECT productid,ProductName,Description,Stock,UOM,Price from ProductTable where productId='" + textBox1.Text + "'", conn);
DataTable dt = new DataTable();
adp.Fill(dt);
foreach (DataRow item in dt.Rows)
{
int i = dataGridView1.Rows.Add();
DataGridViewRow row = dataGridView1.Rows[i];
row.Cells[0].Value = item[0].ToString();
row.Cells[1].Value = item[1].ToString();
row.Cells[2].Value = item[2].ToString();
row.Cells[3].Value = item[3].ToString();
row.Cells[4].Value = item[4].ToString();
row.Cells[5].Value = item[5].ToString();
}
}
And do not forget to close your database connection. Consider using the using-statement for this.
You should also check this: How to add a new row to datagridview programmatically

How do you get the Id of the item in CheckListBox

I have a checkListBox in my windows form application and binded with my database data with SQL. I populate a list of item according to what I select from my comboBox. If I select item 1 from my comboBox, it will display customers' name who is using this item. I want get customers' id according to what I check in my checkListBox.
Here is how I fill my comboBox
private void fill_comboBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
string query = "select itemId, itemName from item_detail";
SqlDataAdapter da = new SqlDataAdapter();
myConn.Open();
DataTable dt = new DataTable();
SqlCommand command = new SqlCommand(query, myConn);
SqlDataReader reader = command.ExecuteReader();
dt.Load(reader);
DataRow dr;
dr= dt.NewRow();
dr.ItemArray = new object[] { 0, "<----------Select an item-------> " };
dt.Rows.InsertAt(dr, 0);
itemComboBox.DataSource = dr;
itemComboBox.ValueMember = "itemId";
itemComboBox.DisplayMember = "itemName";
fill_customerCheckListBox();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is how I fill my checkListBox
private void fill_customerCheckListBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
myConn.Open();
DataSet myDataSet = new DataSet();
myDataSet.CaseSensitive = true;
string commandString = "select fullName from[customer_detail] as cd LEFT JOIN[item_customer] as ic ON ic.customerId= cd.customerI WHERE ic.itemId= '" + itemCombBox.SelectedValue + "' ";
myCommand = new SqlCommand();
myCommand.Connection = myConn;
myCommand.CommandText = commandString;
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
myDataAdapter.SelectCommand = myCommand;
myDataAdapter.TableMappings.Add("Table", "customer_detail");
myDataAdapter.Fill(myDataSet);
DataTable myDataTable = myDataSet.Tables[0];
customerCB.Items.Clear();
string s = "Select All Customer";
customer.Items.Add(s);
foreach (DataRow dataRow in myDataTable.Rows)
{
customerCB.Items.Add(dataRow["fullName"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have a praremter for loop that trying to loop through every checked item from my customerCB, but this isn't working. When I am in my debug mode, the code DataRow row = (itemChecked as DataRowView).Row; is causing an exception
Object reference is not set to an instance of an object.
I have no idea how to fix this. Help will be appreciated, thanks
string parameterList = "";
foreach (object itemChecked in customerCB.CheckedItems)
{
DataRow row = (itemChecked as DataRowView).Row;
parameterList += (parameterList.Length == 0) ? row[0].ToString() : ", " + row[0].ToString();
}
Try the Following way !!
foreach(object itemChecked in checkedListBox1.CheckedItems)
{
DataRowView castedItem = itemChecked as DataRowView;
string fullName= castedItem["fullName"];
}
(OR) You would need to cast or parse the items to their strongly typed equivalents, or use the System.Data.DataSetExtensions namespace to use the DataRowExtensions.Field method demonstrated below:
foreach (var item in checkedListBox1.CheckedItems)
{
var row = (itemChecked as DataRowView).Row;
int id = row.Field<int>("ID");
string name = row.Field<string>("fullName");
}
it seems than when you are populating your combobox your are entering dataRow["fullName"] therefore this cast DataRow row = (itemChecked as DataRowView).Row won't work as itemChecked only contains the value of fullName and not the row, try adding the dataRow instead.

C# All rows from MySQL query not going into datagridview

Im trying to fill a DataGridView with the results from a MySql Query however they are not all going in. Here is my code:
try
{
conn.Open();
player_search = new MySqlCommand("SELECT * FROM admin;", conn);
reader = player_search.ExecuteReader();
int counter = 0;
while (reader.Read())
{
player_list[0, counter].Value = reader.GetString(0);
player_list[1, counter].Value = reader.GetString(1);
player_list[2, counter].Value = reader.GetString(6);
player_list[3, counter].Value = reader.GetString(7);
player_list[4, counter].Value = reader.GetString(8);
player_list[5, counter].Value = reader.GetString(9);
player_list[6, counter].Value = "Remove";
counter = counter+1;
}
}
However it doesnt all go in. It only inserts the first row of the query? Why is it doing this? Im getting no errors?
Solved it! I had to do a long winded approach but it works!
MySqlCommand mysqlcmd = new MySqlCommand("SELECT * FROM admin;", conn);
MySqlDataAdapter mysqlad = new MySqlDataAdapter(mysqlcmd);
DataSet ds = new DataSet();
mysqlad.Fill(ds);
DataTable dt = ds.Tables[0];
player_list.DataSource = dt;
int rowIndex = 0;
foreach (DataRow row in dt.Rows)
{
int i = 0;
foreach (var item in row.ItemArray)
{
if (i == 0) {
player_list[0, rowIndex].Value = item.ToString();
}
if (i == 1) {
player_list[1, rowIndex].Value = item.ToString();
}
if (i == 4)
{
player_list[2, rowIndex].Value = item.ToString();
}
if (i == 7)
{
player_list[3, rowIndex].Value = item.ToString();
}
if (i == 8)
{
player_list[4, rowIndex].Value = item.ToString();
}
if (i == 9)
{
player_list[5, rowIndex].Value = item.ToString();
}
player_list[6, rowIndex].Value = "Remove";
++i;
}
++rowIndex;
i = 0;
}
I would suggest you to try to get it using DataSet:
public DataTable GetDBDataTable(MySqlConnection dbconnection, string table, string columns = "*", string clause = "")
{
MySqlCommand mysqlcmd = new MySqlCommand("SELECT " + columns + " FROM " + table + " " + clause +";", dbconnection);
MySqlDataAdapter mysqlad = new MySqlDataAdapter(mysqlcmd);
DataSet ds = new DataSet();
mysqlad.Fill(ds);
DataTable dt = ds.Tables[0];
return dt;
}
UPDATE: player_list.DataSource(GetDBDataTable(...));
player_list.DataBind();

Connect BindingNavigator with Programmatically Created Datagridview

I have created a datagridview programmatically.
So there is no bindingsource or datasource that we can connect both of the Datagridview and Binidgnavigator to them.
Is there any other way to connect them to each other.
Here is my code for datafridview
Help me to connect it to a bindingNavigator
private void Fill()
{
try
{
if (dataGridView1 != null)
{
dataGridView1.ColumnCount = 11;
dataGridView1.Columns[0].HeaderText = Resources.Form1_Fill_ID;
dataGridView1.Columns[1].HeaderText = Resources.Form1_Fill_Family;
dataGridView1.Columns[2].HeaderText = Resources.Form1_Fill_Cellphone;
dataGridView1.Columns[3].HeaderText = Resources.Form1_Fill_Phone1;
dataGridView1.Columns[4].HeaderText = Resources.Form1_Fill_Phone2;
dataGridView1.Columns[5].HeaderText = Resources.Form1_Fill_Phone3;
dataGridView1.Columns[6].HeaderText = Resources.Form1_Fill_Fax;
dataGridView1.Columns[7].HeaderText = Resources.Form1_Fill_CompanyName;
dataGridView1.Columns[8].HeaderText = Resources.Form1_Fill_Agency;
dataGridView1.Columns[9].HeaderText = Resources.Form1_Fill_Brands;
dataGridView1.Columns[10].HeaderText = Resources.Form1_Fill_Address;
dataGridView1.Columns[0].Name = Resources.Form1_Fill_ID;
dataGridView1.Columns[1].Name = Resources.Form1_Fill_Family;
dataGridView1.Columns[2].Name = Resources.Form1_Fill_Cellphone;
dataGridView1.Columns[3].Name = Resources.Form1_Fill_Phone1;
dataGridView1.Columns[4].Name = Resources.Form1_Fill_Phone2;
dataGridView1.Columns[5].Name = Resources.Form1_Fill_Phone3;
dataGridView1.Columns[6].Name = Resources.Form1_Fill_Fax;
dataGridView1.Columns[7].Name = Resources.Form1_Fill_CompanyName;
dataGridView1.Columns[8].Name = Resources.Form1_Fill_Agency;
dataGridView1.Columns[9].Name = Resources.Form1_Fill_Brands;
dataGridView1.Columns[10].Name = Resources.Form1_Fill_Address;
}
_conn.ConnectionString = _connectionString;
var cmd = new OleDbCommand("Select * from contacts ", _conn);
_conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
int i = 0;
while (reader != null && reader.Read())
{
if (dataGridView1 != null)
{
dataGridView1.Rows.Add(1);
}
if (dataGridView1 != null)
{
var row = dataGridView1.Rows[i];
row.Cells[Resources.Form1_Fill_ID].Value = reader[0].ToString();
row.Cells[Resources.Form1_Fill_Family].Value = reader[1].ToString();
row.Cells[Resources.Form1_Fill_Cellphone].Value = reader[2].ToString();
row.Cells[Resources.Form1_Fill_Phone1].Value = reader[3].ToString();
row.Cells[Resources.Form1_Fill_Phone2].Value = reader[4].ToString();
row.Cells[Resources.Form1_Fill_Phone3].Value = reader[5].ToString();
row.Cells[Resources.Form1_Fill_Fax].Value = reader[6].ToString();
row.Cells[Resources.Form1_Fill_CompanyName].Value = reader[7].ToString();
row.Cells[Resources.Form1_Fill_Agency].Value = reader[8].ToString();
row.Cells[Resources.Form1_Fill_Brands].Value = reader[9].ToString();
row.Cells[Resources.Form1_Fill_Address].Value = reader[10].ToString();
}
i++;
}
}
catch (Exception ex)
{
return;
}
finally
{
_conn.Close();
}
}
Try to revise your code. You don't need to create a column programmactically, your query itself could create a column through DataTable to BindingSource, try this code and get some idea.
BindingNavigator and BindingSource
string connectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=D:\myDatabase.accdb;";
string queryString = "SELECT Name AS FullName, Gender AS Gender, Address AS [Current Address] FROM Person";
using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand(queryString, connection))
{
try
{
BindingSource bs = new BindingSource();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(queryString, connection);
OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(dataAdapter);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
bs.DataSource = dataTable;
dataGridView1.DataSource = bs;
bindingNavigator1.BindingSource = bs;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

How can I loop through an array and populate a datagrid?

Here's the scenario:
I have a multiline text box that I'm reading each line into an array. I'm then looping through that array and sending each value to the stored proc one by one inside the loop and getting a status returned to tell whether it's valid or not.
The issue is I believe I'm overwriting the dataset variable and only populating the datagrid with the last value I retrieve. Is there a better way to achieve what im trying to do? If so, please explain.
protected void submitButton_Click(object sender, EventArgs e)
{
string textLines;
string[] textLine;
textLines = scannedCode.Text;
textLine = textLines.Split(Environment.NewLine.ToArray(), StringSplitOptions.RemoveEmptyEntries);
DataSet ds = null;
Database db = DatabaseFactory.CreateDatabase("ConnectionString");
DataSet ds2 = null;
Database db2 = DatabaseFactory.CreateDatabase("ConnectionString");
foreach (string s in textLine)
{
try
{
DbCommand command2 = db.GetStoredProcCommand("sel_InfoByID_p");
db2.AddInParameter(command2, "#pGuid", DbType.String, s);
ds2 = db2.ExecuteDataSet(command2);
DataGrid1.DataSource = ds2;
DataBind();
}
catch (Exception ex)
{
}
}
}
First, it is possible to merge two dataSets by using the DataSet.Merge method. It means, that you should create a new DataSet outside of the loop and then merge it to a DataSet created by the stored procedure. One more solution is to copy rows from one DataSet to another using the Table's ImportRow method. The latter solution looks better for me. Here is some sample code:
DataTable dt = new DataTable;
...
ds2 = db2.ExecuteDataSet(command2);
for(int i = 0; i < ds2.Tables[0].Rows.Count; i ++)
dt.ImportRow(ds2.Tables[0].Rows[i]);
...
DataGrid1.DataSource = dt;
DataGrid1.DataBind();
Create a DataTable outside and in your for loop add your returned row .
DataTable dt = new DataTable();
///...Add known columns here
Inside for loop add rows to table . After for loop bind table at once.
protected void submitButton_Click(object sender, EventArgs e)
{
string textLines;
string[] textLine;
textLines = scannedCode.Text;
textLine = textLines.Split(Environment.NewLine.ToArray(), StringSplitOptions.RemoveEmptyEntries);
DataSet ds = null;
Database db = DatabaseFactory.CreateDatabase("ConnectionString");
DataSet ds2 = null;
Database db2 = DatabaseFactory.CreateDatabase("ConnectionString");
DataTable dt = new DataTable();
///...Add known columns here
foreach (string s in textLine)
{
try
{
DbCommand command2 = db.GetStoredProcCommand("sel_InfoByID_p");
db2.AddInParameter(command2, "#pGuid", DbType.String, s);
DataRow myNewRow = db2.ExecuteDataSet(command2).tables[0].rows[0];
dt.Rows.Add(myNewRow);
}
catch (Exception ex)
{
}
}
DataGrid1.DataSource = dt;
DataBind();
}
Try This
DataTable obj_Tb=new DataTable();
obj_Tb.Columns.Add("ColumnName");
. //Add Columns as your requirement
.
.
foreach (string s in textLine)
{
try
{
DataRow objrow=obj_Tb.NewRow();
DbCommand command2 = db.GetStoredProcCommand("sel_InfoByID_p");
db2.AddInParameter(command2, "#pGuid", DbType.String, s);
ds2= db2.ExecuteDataSet(command2);
objrow["ColumnName"]=ds2.Table[0].Rows[RowNumber]["ColumnName"].tostring();
//Add Values to all columns as requirement
obj_Tb.Rows.Add(objrow);
}
catch (Exception ex)
{
}
}
DataGrid1.DataSource = obj_Tb;
DataGrid1.DataBind();
Actually your problem was that you are binding the grid on EACH iteration, else nothing wrong with the code. So rather than:
foreach (string s in textLine)
{
try
{
DbCommand command2 = db.GetStoredProcCommand("sel_InfoByID_p");
db2.AddInParameter(command2, "#pGuid", DbType.String, s);
ds2 = db2.ExecuteDataSet(command2);
DataGrid1.DataSource = ds2;
DataBind();
}
catch (Exception ex)
{
}
}
do this:
foreach (string s in textLine)
{
try
{
DbCommand command2 = db.GetStoredProcCommand("sel_InfoByID_p");
db2.AddInParameter(command2, "#pGuid", DbType.String, s);
ds2 = db2.ExecuteDataSet(command2);
}
catch (Exception ex)
{
}
}
DataGrid1.DataSource = ds2;
DataBind();
However, since you're doing looping on the same functionality, for optimizing i suggest:
SqlConnection connection = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand("MyStoredProcName", connection);
command.CommandType = CommandType.StoredProcedure;
SqlParameter submitParam = new SqlParameter("#pGuid", SqlDbType.String);
//use SqlDbType.Bit if you are returning true/false.
SqlParameter returParameter = new SqlParameter("#ReturnedParam", SqlDbType.String);
returParameter.Direction = ParameterDirection.Output;
connection.Open();
foreach (string s in textLine)
{
returnString.Value = s;
command.Parameters.Clear();
command.Parameters.Add(submitParam);
command.Parameters.Add(returParameter);
try
{
command.ExecuteNonQuery();
store the returned string in DataTable, BindingList<string> or any, but this is how to retrieve it:
Convert.ToString(Command.Parameters["#ReturnedParam"].Value, CultureInfo.CurrentCulture)
}
catch (Exception ex)
{
;;
}
}
connection.Close();
Do the grid binding here

Categories