Why can't I load database values onto my listview? - c#

I have this code:
listView10.Items.Clear();
MySqlConnection con = new MySqlConnection("Server=166.62.27.186;Database=xxxx;Uid=xxxx;Pwd=xxxx;");
MySqlCommand cmd = new MySqlCommand("select * from appoint order by times asc", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
con.Open();
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
ListViewItem Item = new ListViewItem(dr["Customer"].ToString());
Item.SubItems.Add(dr["Kind"].ToString());
Item.SubItems.Add(dr["connum"].ToString() + "/" + dr["telnum"].ToString());
Item.SubItems.Add(dr["times"].ToString());
Item.SubItems.Add(dr["address"].ToString());
Item.SubItems.Add(dr["type"].ToString());
Item.SubItems.Add(dr["notes"].ToString());
listView10.Items.Add(Item);
}
con.Close()
it should load the value in the table but it doesn't.
When I connected the database to the Mysql Workbench it seems the connection is working. in my winform application it can insert into the database yet it still doesnt load. i as i observed I noticed that after executing :
da.Fill(dt);
It just stops there and doesn't execute the foreach statement. What seems to be the problem i don't understand.
I will provide more information if needed, im kinda in a rush tomorrow is our defense in our thesis. thanks in advance
pics when debugging

You can use DataTable.Load() method with MySqlDataReader.ExecuteReader() method as alternative to MySqlDataAdapter to retrieve data like this example:
using (MySqlConnection con = new MySqlConnection("Server=166.62.27.186;Database=xxxx;Uid=xxxx;Pwd=xxxx;"))
{
con.Open();
using (MySqlCommand cmd = new MySqlCommand("select * from appoint order by times asc", con))
{
MySqlDataReader rdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow dr in dt.Rows)
{
ListViewItem Item = new ListViewItem(dr["Customer"].ToString());
Item.SubItems.Add(dr["Kind"].ToString());
Item.SubItems.Add(dr["connum"].ToString() + "/" + dr["telnum"].ToString());
Item.SubItems.Add(dr["times"].ToString());
Item.SubItems.Add(dr["address"].ToString());
Item.SubItems.Add(dr["type"].ToString());
Item.SubItems.Add(dr["notes"].ToString());
listView10.Items.Add(Item);
}
}
con.Close();
}

Related

How to display the proper data?

I have 2 datagridviews now i want to select a column named "Name" in the first datagridview and us it as the WHERE in my query to Select values from a table and put it in the other datagridview.
SqlCommand cmd = new SqlCommand();
cmd = ss.CreateCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
ss.Open();
cmd.CommandType = CommandType.Text;
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '" +
row.Cells[4].Value.ToString() + "' ";
cmd.CommandText = Query;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter dp = new SqlDataAdapter(cmd);
dp.Fill(dt);
dgvSign.DataSource = dt;
ss.Close();
}
but it gives me error when there is null and it is only selecting the first row in the first datagridview.
You create in each foreach-loop a new DataTable and therefore it will always just have one Value. So you have to create it before the foreach-loop.
And make sure you check the Values you want to use before using them.
With this easy if-condition, there won't be any problems.
Edit1:
This code snippet is working just fine.
Just change the ConnectionString and you are done.
DataTable dt = new DataTable();
string error;
using (SqlConnection con = new SqlConnection(#"Data Source=SERVER;Initial Catalog=DATEBASE; User ID=USERNAME; Password=PASSWORD"))
{
SqlCommand cmd = new SqlCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '";
if (row.Cells.Count >= 4 && row.Cells[4].Value != null)
{
Query += row.Cells[4].Value.ToString();
}
Query += "'";
try
{
cmd = new SqlCommand(Query, con);
if (con.State == ConnectionState.Closed)
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
catch (Exception ex)
{
error = ex.Message;
}
}
}
dgvSign.DataSource = dt;

C# Show list in combobox based on selection in first combobox

Good day.
I just looking for a solution to my problem. I just trying to make my first program and I have encountered this problem. I have 2 comboboxes, the first one is the list of supplier and the second one is the list of items. Now I need to filter down what will show in the 2nd combobox based on the 1st combobox, but still in the 2nd combobox. It always shows all the item that is listed from my database. All data are coming from SQL Database and below is the code that I am working with:
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tblmaster where Supplier = '" + comboBox3.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
foreach(DataRow dr in dt.Rows) {
comboBox5.Items.Add(dr["ProductCode"].ToString());
}
conn.Close();
}
Try to clear the items before the loop.
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tblmaster where Supplier = '" + comboBox3.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
comboBox5.Items.Clear();
foreach(DataRow dr in dt.Rows) {
comboBox5.Items.Add(dr["ProductCode"].ToString());
}
conn.Close();
}

Read Excel named range from C#

I am trying to read a named range from my excel as per below:
conn.Open();
using (OleDbCommand cmd1 = new OleDbCommand("SELECT * FROM [NamedRange]"))
{
cmd1.Connection = conn;
//conn.Open();
var result = cmd1.ExecuteReader();
while (result.Read())
{
var str = result[0].ToString();
}
}
The code runs but the while loop gets skipped. I know my named range should be read because this method works:
OleDbDataAdapter da2 = new OleDbDataAdapter("Select * from [NamedRange]”, conn);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
foreach (DataColumn Col in dt2.Columns)
{var str = Col.Caption}
I cannot figure out why the first method does not work.
For everyone who is still looking for a solution, change your query like this:
OleDbCommand cmd1 = new OleDbCommand("SELECT * FROM [sheetName$][NamedRange]")
I hope this helps!

SQL timeout exception

Why do I get this exception in my code? I restarted the server, changed ports, etc, but nothing is working.
What's wrong?
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection("server=localhost;user=armin;password=root;");
con.Open();
SqlCommand result = new SqlCommand(
"SELECT userid FROM KDDData.dbo.userprofile order by userid", con);
SqlDataReader reader = result.ExecuteReader();
dt.Load(reader);
List<string> userids = new List<string>(dt.Rows.Count);
foreach (DataRow item in dt.Rows)
{
userids.Add(item.ItemArray[0].ToString().Trim());
}
con.Close();
con = new SqlConnection("server=localhost;user=armin;password=root;");
con.Open();
foreach (string user in userids)
{
DataTable temp = new DataTable();
SqlCommand result1 = new SqlCommand(
"select itemid from KDDTrain.dbo.train where userid=" + user, con);
SqlDataReader reader1 = result1.ExecuteReader();
if (!reader1.HasRows)
{
continue;
}
temp.Load(reader1);
}
The first query works fine, but the second doesn't. As you can see I even use some other SqlConnection but it still doesn't work.
Note:The database i'm working with has atleast 100 milion records,thought may be this would be a problem.
Something doesn't look right in your connection string
I always seen "server=localhost; user=armin;password=root" in connections strings for MySql not for SqlServer where instead I will use "Data Source=(LOCAL);Integrated Security=SSPI" or the INSTANCE name of SqlServer. Are you sure that the first query works?.
However I think you should use the appropriate using statement
DataTable dt = new DataTable();
using(SqlConnection con = new SqlConnection("server=localhost;user=armin;password=root;"))
{
using(SqlCommand result = new SqlCommand(
"SELECT userid FROM KDDData.dbo.userprofile order by userid", con))
{
con.Open();
using(SqlDataReader reader = result.ExecuteReader())
{
dt.Load(reader);
List<string> userids = new List<string>(dt.Rows.Count);
foreach (DataRow item in dt.Rows)
{
userids.Add(item.ItemArray[0].ToString().Trim());
}
}
DataTable temp = new DataTable();
foreach (string user in userids)
{
using(SqlCommand result1 = new SqlCommand(
"select itemid from KDDTrain.dbo.train where userid=" + user, con))
{
using(SqlDataReader reader1 = result1.ExecuteReader())
{
if (!reader1.HasRows) continue;
temp.Load(reader1);
}
}
}
}
Please insert this line
result1.CommandTimeout = 0;
befor this line in the second query
SqlDataReader reader1 = result1.ExecuteReader();
Dispose your reader after:
foreach (DataRow item in dt.Rows)
{
userids.Add(item.ItemArray[0].ToString().Trim());
}
...and also close the connection after temp.Load(reader1). Also close the reader1.
Instead of all this... the clean way is to use USING for initializng the readers and connection. :)

How to insert a row using a IDbDataAdapter(SqlDataAdapter or OleDbDataAdapter) without loading the entire table?

I need to insert a row into a DataTable using a OleDbDataAdapter. However, my table has more than 100000 records and I don't want to load all the records.
My current code loads all the records into the DataTable
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Nodes", _cnAq9);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr = dt.NewRow();
dr["nID"] = nNodeID;
dr["csNumber"] = strNumber;
dt.Rows.Add(dr);
da.Update(dt);
Is there a way to insert data into my table without filling my datatable with all the rows other than adding "where 1 = 0" to my statement
EDIT
I need to use a DataAdapter to do this
Call FillSchema instead of Fill
As per request:
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Nodes", _cnAq9);
DataTable dt = new DataTable();
da.FillSchema(dt, SchemaType.Source);
DataRow dr = dt.NewRow();
dr["nID"] = nNodeID;
dr["csNumber"] = strNumber;
dt.Rows.Add(dr);
da.Update(dt);
Yes, by using the DbCommand class to execute an INSERT.
Your code will probably look something like
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
var query = "INSERT INTO Nodes (nID, csNumber) " +
"VALUES (?, ?)";
var command = new OleDbCommand( query, connection);
command.Parameters.AddWithValue("#nID", nNodeID);
command.Parameters.AddWithValue("#csNumber", strNumber);
connection.Open();
command.ExecuteNonQuery();
}
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Nodes", _cnAq9);
DataTable dt = new DataTable();
da.FillSchema(dt, SchemaType.Source);
DataRow dr = dt.NewRow();
dr["nID"] = nNodeID;
dr["csNumber"] = strNumber;
dt.Rows.Add(dr);
da.Update(dt);
try
oleconnStkNames = new OleDbConnection(strAccessConnectionString);
oleconnStkNames.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = oleconnStkNames; //new OleDbConnection(strAccessConnectionString);
cmd.CommandText = "TheName of your InsertQuery "; // name of the query you want to run
cmd.CommandType = CommandType.StoredProcedure; // or System.Data.CommandType.Text if you are not using a Access StoredProc
OleDbDataReader rdr = cmd.ExecuteReader();
catch (Exception ex)
{
bla..bla..bla
}
//if you want to wrap it in a using() and add transactional processing use this example that I've written to fit what ever it is you are doing..
using (OleDbCommand olecmdStkNames = new OleDbCommand(strSQL, oleconnStkNames))
{
olecmdStkNames.CommandTimeout = 60;
oletransStockList = oleconnStkNames.BeginTransaction();
olecmdStkNames.Transaction = oletransStockList;
olecmdStkNames.CommandType = System.Data.CommandType.Text;
try
{
intRecordsAffected = olecmdStkNames.ExecuteNonQuery();
oletransStockList.Commit();
}
catch (OleDbException oledbExInsert_Update)
{
oletransStockList.Rollback();
Console.WriteLine(oledbExInsert_Update.Message);
}
((IDisposable)oletransStockList).Dispose();
}

Categories

Resources