Display rows retrieved from a database in seperate textboxes - c#

I have a MySQL database with about 40 rows.
I want to read "value" each into its own textbox.
What I have so far
using (var cmd2 = new OdbcCommand("select value,entity_id,store_id from catalog_category_entity_varchar where attribute_id = 41 ", con))
{
con.Open();
using (var reader = cmd2.ExecuteReader())
{
while (reader.HasRows)
{
int count = reader.FieldCount;
for (int i = 0; i < count; i++)
{
while (reader.Read())
{
textBox[i].txt = (reader[0].ToString());
this.Controls.Add(textBox[i].txt);
reader.NextResult();
}
}
}
I only get the first record into a textbox.
Assume that the amount of rows is unknown.
If there is 40 rows, there must be 40 textboxes.
I've edited my code to:
using (var reader = cmd2.ExecuteReader())
{
int i = 0;
while (reader.HasRows)
{
TextBox txt = new TextBox();
txt.Text = reader.GetString(0);
this.Controls.Add(txt);
textBox[i].txt = (reader.GetString(0));
this.Controls.Add(textBox[i].txt);
reader.NextResult();
i++;
}
}
The error that I get is : error - the name textbox does not exist in the current context

If your textBox is an array of controls
con.Open(); -- you need open the connection before the command
using (var cmd2 = new OdbcCommand("select value,entity_id,store_id
from catalog_category_entity_varchar
where attribute_id = 41 ", con))
{
using (var reader = cmd2.ExecuteReader())
{
int i = 0;
while (reader.Read())
{
TextBox txt = new TextBox();
txt.Text = reader.GetString(0);
txt.Location.x = 100;
txt.Location.y = 100 * i;
this.Controls.Add(txt);
i++;
}
If you havent create the textbox already you need
TextBox txt = new TextBox();
txt.Text = reader.GetValue(0);
txt.Location.x = 100;
txt.Location.y = 100 * i;
this.Controls.Add(txt);

Related

Improve SQL query execution time

I have a dataGridView that displays data from a table, after I export these data as a xml file, I add the unique field to another table so I can display only non-exported data.
How I display only data that are not yet exported :
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
SqlCommand queryLocal = new SqlCommand("SELECT *uniqueField* FROM myTable
WHERE *uniqueField* = " + dataGridView1.Rows[i].Cells[3].Value.ToString().Trim().Replace("'","''"), con);
var reader = queryLocal.ExecuteReader();
if (reader.Read())
{
dataGridView1.Rows.RemoveAt(i);
i--;
}
reader.Close();
}
The problem is that it takes more than 20 seconds to filter less than 400 rows.
How could I improve the performance here ?
You could try this:
SqlCommand queryLocal = new SqlCommand("SELECT DISTINCT *uniqueField* FROM myTable");
var reader = queryLocal.ExecuteReader();
List<string> uniqueFields = new List<string>();
while (reader.Read())
uniqueFields.Add(reader[0]);
reader.Close();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (uniqueFields.Contains(dataGridView1.Rows[i])
{
dataGridView1.Rows.RemoveAt(i);
i--;
}
}

read data in database to checkboxlist, how can i read it?

How can I read the data in the database so when it reads. it will check the specific data?
Here is my full code:
string query = "SELECT TypeName from TypeTransaction WHERE UANumber = '" + id + "'";
connUser.Open();
cmd.CommandText = query;
sdr = cmd.ExecuteReader();
while(sdr.Read())
{
ListItem item = new ListItem();
item.Text = sdr.GetString(0);
lbTypes.Items.Add(item);
}
List<string> iteme = new List<string>();
for(int j = 0; j < lbTypes.Items.Count; j++)
{
for(int i = 0;i < chkTypes.Items.Count;i++)
{
if(lbTypes.Items[j].Text == chkTypes.Items[i].Text)
{
chkTypes.Items[i].Selected = true;
}
else
{
chkTypes.Items[i].Selected = false;
}
}
}
my listbox has a value of GDS and Email in a seperate line, but when i run it, the Email Checkbox is the one only selected. it should be both Email and GDS that is selected in the checkboxlist.
Take a look on below url which helps you
http://www.aspsnippets.com/Articles/Bind-CheckBoxList-from-Database-in-ASPNet.aspx

Can't get the total row count

I have a table which has 3 columns and each column has 5 rows.Now I wanna get those total numbers of rows in c# to create that number of labels dynamically as well as get the rows value for labels name.Similarly, creates same numbers of the textbox as well.Then in the runtime, i wanted to submit the value to the database by this textbox.
Note: here, if I increase the rows of the table,then the label and textbox will be increased automatically/dynamically as well as submitting value through textbox will perfectly work.
But , all I have done is only getting count value 1 , I just tried a lot but not getting the total count value which is actually 5 .
here, is my code...
private void Form1_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
//string cmText = "select ProductId,ProductName,UnitPrice from tblProductInventory";
string cmText = "Select Count(ProductId) from tblProductInventory";
SqlCommand cmd = new SqlCommand(cmText, con);
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
int count = rdr.FieldCount;
while (rdr.Read())
{
//System.Windows.Forms.Label MyLabel;
{
int y = 50;
Label myLabel = new Label();
for (int i = 0; i < count; i++)
{
myLabel = new Label();
myLabel.Location = new Point(88, y);
myLabel.Name = "txtVWReadings" + i.ToString();
myLabel.Size = new Size(173, 20);
myLabel.TabIndex = i;
myLabel.Visible = true;
myLabel.Text = rdr[i].ToString();
y += 25;
this.Controls.Add(myLabel);
}
}
}
}
}
}
And I got this output.
The issue seems that you are using query as count but you want the values of the field. So you can probably change it to
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
//string cmText = "select ProductId,ProductName,UnitPrice from tblProductInventory";
string cmText = "Select Count(ProductId) from tblProductInventory";
SqlCommand cmd = new SqlCommand(cmText, con);
con.Open();
Int32 count = (Int32) cmd.ExecuteScalar();
int i = 1;
cmText = "select ProductId,ProductName,UnitPrice from tblProductInventory";
SqlCommand cmd1 = new SqlCommand(cmText, con);
using (SqlDataReader rdr = cmd1.ExecuteReader())
{
int y = 50;
Label myLabel = new Label();
TextBox MyTxt = New TextBox();
while (rdr.Read())
{
myLabel = new Label();
myLabel.Location = new Point(88, y);
myLabel.Name = "txtVWReadings" + i.ToString();
myLabel.Size = new Size(173, 20);
myLabel.TabIndex = i;
myLabel.Visible = true;
myLabel.Text = rdr[1].ToString(); //Since you want ProductName here
y += 25;
this.Controls.Add(myLabel);
//Same Way Just include the TextBox
//After all Position of TextBox
MyTxt.Text = rdr[2].ToString(); // I believe you need UnitPrice of the ProductName
i++;
}
}
}
Count(columname) :
Will count only the NOT NULL values in that column.
Count(*) :
Will count the number of records in that table.
So I guess you have some NULL values in ProductId column. Change it to
Select Count(*) from tblProductInventory

Reading the status (Checked/Unchecked) of a CheckBoxList checkbox

I am currently using a databound CheckBoxList and I need to identify the status of what checkbox was checked, and unchecked, etc. Basically when a user presses a checkbox it autopostbacks, I read some data from the database, and have a running Session with totals. What I need is when a checkbox is unchecked to identify this change, also make a database call, and substract the amount that product is supposed to cost. Or maybe just read every checkbox everytime a checkbox is checked/unchecked but I'd think that's less optimal.
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
decimal CompraTotal = 0;
MySqlConnection connection = new MySqlConnection(GlobalVars.mysql);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "QUERY";
command.Parameters.AddWithValue("?GUID", Session["GUID"]);
command.Parameters.AddWithValue("?Name", CheckBoxList1.SelectedValue);
MySqlDataReader reader = command.ExecuteReader();
decimal Price = 0;
while (reader.Read())
{
Price = Convert.ToDecimal(reader["Price"]);
}
Total = Convert.ToDecimal(Session["Total"]);
Total = Total + Price;
Session["Total"] = Total;
}
I just need to identify what checkbox was unchecked and run a similar query to substract from the total. THanks for any help :)
EDIT: Updated code (made some adjustments to variables and stuff as well):
if (Session["previouslySelected"] != null && Session["previouslySelected"].ToString() != "-1")
{
decimal CompraTotal2 = 0;
MySqlConnection connection = new MySqlConnection(GlobalVars.mysql);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "QUERY";
command.Parameters.AddWithValue("?GUID", Session["GUID"]);
command.Parameters.AddWithValue("?Nombre", CheckBoxList1.SelectedValue);
MySqlDataReader reader = command.ExecuteReader();
decimal Precio = 0;
while (reader.Read())
{
// reader.GetString(0);
Precio = Convert.ToDecimal(reader["Precio"]);
}
CompraTotal2 = Convert.ToDecimal(Session["CompraTotal"]);
CompraTotal2 = Precio - CompraTotal2;
Session["CompraTotal"] = CompraTotal2;
}
if (CheckBoxList1.SelectedIndex != -1)
{
decimal CompraTotal = 0;
MySqlConnection connection = new MySqlConnection(GlobalVars.mysql);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "QUERY";
command.Parameters.AddWithValue("?GUID", Session["GUID"]);
command.Parameters.AddWithValue("?Nombre", CheckBoxList1.SelectedValue);
MySqlDataReader reader = command.ExecuteReader();
decimal Precio = 0;
int i = 0;
while (reader.Read())
{
// reader.GetString(0);
Precio = Convert.ToDecimal(reader["Precio"]);
}
CompraTotal = Convert.ToDecimal(Session["CompraTotal"]);
CompraTotal = CompraTotal + Precio;
Session["CompraTotal"] = CompraTotal;
}
Session["previouslySelected"] = CheckBoxList1.SelectedIndex;
Label3.Text = Convert.ToString(Session["CompraTotal"]);
}
The problem I am facing know is that the first part of the code also executes at the same time as the other one, giving me bad values. I have two items databound to my CheckList, I have Option 1 and Option 2. I concatenated the values for the text since there are prices, so what I am displaying is Option 1 $1.00 Option 2 $0.50. With the query I get a specific GUID and since the name is unique I look up the Price value. If the checkbox was unchecked it should check for that value, then subtract from the current total. If the checkbox was checked it should then look for that value and add it.
FINAL FIXED CODE FOR THOSE WHO ARE IN THE SAME SITUATION
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected)
{
values += CheckBoxList1.Items[i].Value + ",";
\\COMMANDS EXECUTE HERE
}
}
if (Session["previouslySelected"] != null && Session["previouslySelected"].ToString() != "-1")
{
decimal CompraTotal2 = 0;
MySqlConnection connection = new MySqlConnection(GlobalVars.mysql);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "QUERY";
command.Parameters.AddWithValue("?GUID", Session["GUID"]);
command.Parameters.AddWithValue("?Nombre", Session["previouslySelected"].ToString());
MySqlDataReader reader = command.ExecuteReader();
decimal Precio = 0;
while (reader.Read())
{
// reader.GetString(0);
Precio = Convert.ToDecimal(reader["Precio"]);
}
CompraTotal2 = Convert.ToDecimal(Session["CompraTotal"]);
CompraTotal2 = Precio - CompraTotal2;
Session["CompraTotal"] = CompraTotal2;
}
if (CheckBoxList1.SelectedIndex != -1)
{
decimal CompraTotal = 0;
MySqlConnection connection = new MySqlConnection(GlobalVars.mysql);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "QUERY";
command.Parameters.AddWithValue("?GUID", Session["GUID"]);
command.Parameters.AddWithValue("?Nombre", CheckBoxList1.SelectedValue);
MySqlDataReader reader = command.ExecuteReader();
decimal Precio = 0;
int i = 0;
while (reader.Read())
{
// reader.GetString(0);
Precio = Convert.ToDecimal(reader["Precio"]);
}
CompraTotal = Convert.ToDecimal(Session["CompraTotal"]);
CompraTotal = CompraTotal + Precio;
Session["CompraTotal"] = CompraTotal;
}
Session["previouslySelected"] = CheckBoxList1.SelectedIndex;
Label3.Text = Convert.ToString(Session["CompraTotal"]);
}

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.

Categories

Resources