c# eliminatig over spaces in richtextbox output - c#

I have some problems with spaces, i don't know how to solve it. It should be like this:
But it's actually like this:
public void azurirajPodatke()
{
richTextBox1.Clear();
try
{
con.Open();
string kom = "select * from Pecaros order by PecarosID asc";
cmd = new SqlCommand(kom, con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
string id = dr[0].ToString();
string ime = dr[1].ToString();
string prezime = dr[2].ToString();
string adresa = dr[3].ToString();
string telefon = dr[4].ToString();
string grad = dr[5].ToString();
string linija = string.Format(
"{0,-15}|{1,-10}|{2,-15}|{3,-15}|{4,30}|{5,-15}",
id, ime, prezime, adresa, telefon, grad);
richTextBox1.Text += linija+"\n";
}
dr.Close();
}
}

First, you need to wrap all of the objects (textbox, labels, and etc) inside a groupBox object as shown in my image. This will allow you to configure padding and margins to control the distance your objects are away from another. Then, change the formBorderStyle to "FixedSingle" I would change the "MaximizeBox" to false. Then, change the textbox to a ListView or DataGrid. Finally, when you adjust the form size, it will rearrange the objects how you want them.

Related

How to change label's text depending on item selected on a combo box which is populated using SQLite?

I have a button that creates 6 controls for the columns of a TableLayoutPanel, the 6 columns are: Order Number, Product Name (Combo Box), Current Quantity (Label), Quantity Bought, New Quantity, and Delete Row.
The combo box is populated using SQLite. For the Variants table, I have 7 columns: [Product Name], Name, [Serial Number], [Stock On Hand], [Sell Before].
How can I make it so that, the labels under "Current Quantity" changes depending on the [Stock On Hand] of the selected item on the combo box?
On my current code an error of "Index was outside the bounds of the array" shows every time I choose in the combo box.
Code for creating dynamic combo box:
ComboBox cboItemName = new ComboBox
{
Name = "cboItemName" + rowIndex,
Dock = DockStyle.Fill,
DropDownStyle = ComboBoxStyle.DropDownList
};
cboItemName.SelectedIndexChanged += new EventHandler(cboItemName_SelectedIndexChanged);
tblOrders.Controls.Add(FillComboBox(cboItemName));
Code for the event handler of the combo box:
void cboItemName_SelectedIndexChanged(object sender, EventArgs e)
{
var cbo = (ComboBox)sender;
string name = cbo.Name;
string splittedString = new String(name.Where(Char.IsDigit).ToArray());;
string labelName = "lblCurrentQuantity" + splittedString;
string selectedIndex = cbo.SelectedIndex.ToString();
string selectedItem = cbo.SelectedItem.ToString();
Label tbx = tblOrders.Controls.Find(labelName, true).FirstOrDefault() as Label;
EditLabelCurrentQuantity(tbx, selectedItem);
}
And, lastly, code for the changing of label's text:
private void EditLabelCurrentQuantity(Label label, string itemSelected)
{
auth = new Authentication();
auth.getConnection();
try
{
using (SQLiteConnection con = new SQLiteConnection(auth.connectionString))
{
con.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.CommandText = #"SELECT [Stock On Hand] FROM Variants WHERE Name='" + itemSelected + "'";
cmd.Connection = con;
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string name = Convert.ToString(reader["[Stock On Hand]"]);
}
con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I have finally figured it out, if anyone ever did come across something to my bad design, I have fixed this by adding this:
string name = Convert.ToString(reader[0]);
labelCategory.Text = name;
in:
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string name = Convert.ToString(reader["[Stock On Hand]"]);
}

How do i make a sql select dynamic string comparison to work?

I´m trying to get the correct string from a wpf datagrid clicked cell that i will use in a sql select statement to a second wpf datagrid.
When entering a static string value it will work, but not from a dynamic string. What is wrong with my code?
private void dataGrid1_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
DataRowView row = (DataRowView)dataGrid1.SelectedItems[0];
string barcode_string = row["BarCode"].ToString();
//string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = '" + barcode_string + "'";
string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = 'L002BO4'";
}
When entering the string in the sql statement it works like a charm, but ofcourse i want the dynamic string returned from the large database work as well.
Please do not concatenate strings in SQL statements. Use parameters. Check your database for the correct data type of the BarCode column.
private void DataGrid1_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
DataTable dt = new DataTable();
DataRowView row = (DataRowView)dataGrid1.SelectedItems[0];
string barcode_string = row["BarCode"].ToString();
//string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = '" + barcode_string + "'";
string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = #BarCode;";
using (SqlConnection cn = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand(barcode_detail, cn);
cmd.Parameters.Add("#BarCode", System.Data.SqlDbType.VarChar).Value = barcode_string;
cn.Open();
dt.Load(cmd.ExecuteReader());
//use the data in the data table
}
}
EDIT
Test the strings. Add using System.Diagnostics to use Debug.Print
String literal = "L002BO4";
String variable = row["BarCode"].ToString();
if (literal.Length == variable.Length)
Debug.Print("The length of the strings match");
else
Debug.Print("The lengths do not match");
Char[] variableArray = variable.ToCharArray();
Char[] literalArray = literal.ToCharArray();
for (int index =0; index<literalArray.Length; index++)
{
if (variableArray[index] == literalArray[index])
Debug.Print($"index {index} matches");
else
Debug.Print($"index {index} does not match");
}
You just missed one " at the last of your query. Try this
string barcode_detail = "SELECT BarCode, PCBGUID
FROM TB_AOIResult WHERE
BarCode = "+"\'" +barcode_string + "\'";
Can you try like below
string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = "+ barcode_string;

database values in textbox

If the voucher number that I typed exists in the table, it should show the details in the respective textboxes, but if it doesn't exist a message box that says (ID doesn't exists! ) would show.
For example, the voucher number 101 exists in the table,
First,I would type '1' in the textbox , the messagebox would immediately appear ...
Second I would continue the number after clicking ok it will now be number "10" a messagebox will again appear that says (ID doesn't exists! ). Then finally I would be able to type "101" the details would already show in the respective textboxes.
My problem is that when everytime that I typed a single number, a messagebox that says (ID doesn't exists! ) appears. How do I solve that?
textchanged property of "textBox22" code:
private void textBox22_TextChanged(object sender, EventArgs e)
{
String path = "Data Source=LOCALHOST; Initial Catalog= sadd; username=root; password=''";
MySqlConnection sqlconn = new MySqlConnection(path); //communicator //constructors
MySqlCommand sqlcomm = new MySqlCommand();
MySqlDataReader sqldr;
sqlconn.Open();
sqlcomm.Connection = sqlconn;
sqlcomm.CommandType = CommandType.Text;
sqlcomm.CommandText = "Select * from approvedrecords where VoucherNumber=" + textBox22.Text + "";
sqldr = sqlcomm.ExecuteReader();
sqldr.Read();
if (sqldr.HasRows)
{
textBox26.Text = sqldr[0].ToString();
}
sqlconn.Close();
if (textBox22.Text == textBox26.Text)
{
String path8 = "Data Source=LOCALHOST; Initial Catalog= sadd; username=root; password=''";
MySqlConnection sqlcon = new MySqlConnection(path8); //communicator //constructors
string query = "select * from approvedrecords where VoucherNumber = " + textBox22.Text + " ";
MySqlCommand cmd = new MySqlCommand(query, sqlcon);
MySqlDataReader dbr;
sqlcon.Open();
dbr = cmd.ExecuteReader();
while (dbr.Read())
{
string a = (string)dbr["CheckNumber"].ToString();
string b = (string)dbr["DateCreated"];
string c = (string)dbr["Status"];
string d = (string)dbr["PayeesName"];
string f = (string)dbr["Amount"].ToString();
string g = (string)dbr["DatePrinted"];
string h = (string)dbr["Particulars"];
string i = (string)dbr["Prepared_by"];
string j = (string)dbr["Payment_received_by"];
textBox21.Text = a;
textBox23.Text = b;
textBox28.Text = c;
textBox20.Text = d;
textBox19.Text = f;
textBox27.Text = g;
textBox18.Text = h;
textBox16.Text = i;
textBox17.Text = j;
}
}
else
{
MessageBox.Show("ID doesn't exist!");
}
Why don't you try using the OnLostFocus event of the textbox? As explained here. That way your code would be called only when the user abandons your textbox.
Alternatively, if you want to keep your OnTextChanged handler, I would recommend using async calls my adding an UpdatePanel as explained here. You would need to add a label showing the status of the query every time the user typed in a character, so when no data is returned by your query, the label would show "No results found for this ID" and no textboxes would be populated. When results are found, then the label would read "Data was found for this ID" and you would populate the controls accordingly.
I hope this helps and I hope I was clear :-)

Target a label whos ID is structured as "lblx1" by doing lblx + variable

I have a few labels on my site, which i need to populate with specific values from a database. So I've used a naming convention such as "lblx1", "lblx2", "lblx3" etc. and planned to do the following in a while loop:
lblx + id.Text = dbVariable
but this can't work as the code needs the name of an existing label in full.
public void beanList()
{
SqlCommand comm = new SqlCommand("SELECT id,Price250g,Price1kg FROM Beans", conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
string id = reader["id"].ToString();
string price250g = reader["Price250g"].ToString();
string price1kg = reader["Price1kg"].ToString();
lbl250 + id.Text = price250g;
lbl1 + id.Text = price1kg;
}
}
I have also attempted from an anwser:
public void beanList()
{
SqlCommand comm = new SqlCommand("SELECT id,Price250g,Price1kg FROM Beans", conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
string id = reader["id"].ToString();
string price250g = reader["Price250g"].ToString();
string price1kg = reader["Price1kg"].ToString();
Label l250g = new Label();
l250g.ID = "lbl250" + id;
l250g.Text = price250g;
Label l1kg = new Label();
l1kg.ID = "lbl1" + id;
l1kg.Text = price1kg;
}
}
But this does nothing, when stepping through "l250g.ID" is set, but "l250g.Text" doesn't work. It runs but is setting the text of the label whos ID it has been given.
Is there a way to get this to work without having to do a separate database query for each label, as the attempted while loop method is ideal as it would be fastest instead of calling the query X amount of times.
Create a List<string, Label>, like this:
List<KeyValuePair<string, Label>> elements = new List<KeyValuePair<string, Label>>();
Whenever you add an element, you do this:
elements.Add(new KeyValuePair<string, label>("lblx" + ids.Count, myLabel));
basically you need to find the control first. Hope the below code hint helps
string[] id = new string(1);
id[0] = reader["id"].ToString();
string price250g = reader["Price250g"].ToString();
string price1kg = reader["Price1kg"].ToString();
string templabel = null;
foreach (string i in id)
{
templabel = lbx + i;
var matches = this.Controls.Find(templabel, true).GetValue(0);
((Label)matches).Text = price250g;
}
I have specified GetValue(0) for my test. You can take a counter in your case.

How to use WHILE in ASP.NET

When retrieving 5 values using LIMIT 0,5 and WHILE how to set these five values in five different ASP.NET text boxes? using the following code I am able to write as Response.Write but how to fix them in TextBox?
OdbcCommand cmd = new OdbcCommand(
"Select nickname, city, country, zipcode from awm_profiles WHERE email LIKE '%softmail.me%' LIMIT 0 , 30",
MyConnection);
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
//throw new Exception();
}
while (dr.Read())
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
string d = dr[3].ToString();
Response.Write(a);
Response.Write(b);
Response.Write(c);
Response.Write(d);
}
Use some data-driven control like GridView. Check this video: [How Do I:] Create Data-Driven Web Sites?
In your case texboxes will have values only from the last row.
Place TextBox Controls in the ASPX page and then set the value using the textbox's ID:
tb1.Text = a;
instead of Response.Write(a); put your textbox
TextBox1.Text = a;
TextBox2.Text = b; like that
Use a Data Repeater control.
or you can use like this
OdbcCommand cmd = new OdbcCommand(
"Select nickname, city, country, zipcode from awm_profiles WHERE email LIKE '%softmail.me%' LIMIT 0 , 30",
MyConnection);
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
//throw new Exception();
}
StringBuilder builder = new StringBuilder();
while (dr.Read())
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
string d = dr[3].ToString();
builder.AppendLine(a);
builder.AppendLine(b);
builder.AppendLine(c);
builder.AppendLine(d);
}
Response.Write(bulder.ToString());
Hope this will help :)

Categories

Resources