Label does not populate - c#

I have this code to receive a number from user through a text box, then use that value and two values from a SQL table and perform a simple calculation. I debugged and get no errors but my label in gridview does not populate. Any help would be greatly appreciated.
protected void Calculate_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT [Divide], [Calc] FROM [Parrts] WHERE (([Region] = 'East Coast') AND ([Model] = #Model) AND ([SashSize] = #SashSize) AND ([Operation] = #Operation) AND ([PartDesc] = #PartDesc) AND ([Description] = #Description) AND ([Lites] =#Lites))", conn);
SqlParameter Model = new SqlParameter("#Model", ddModel.SelectedValue);
cmd.Parameters.Add(Model);
SqlParameter SashSize = new SqlParameter("#SashSize", ddSashSize.SelectedValue);
cmd.Parameters.Add(SashSize);
SqlParameter Operation = new SqlParameter("#Operation", ddOperation.SelectedValue);
cmd.Parameters.Add(Operation);
SqlParameter Part = new SqlParameter("#PartDesc", ddPart.SelectedValue);
cmd.Parameters.Add(Part);
SqlParameter Color = new SqlParameter("#Description",ddColor.SelectedValue);
cmd.Parameters.Add(Color);
SqlParameter Lites = new SqlParameter("#Lites",ddLites.SelectedValue);
cmd.Parameters.Add(Lites);
conn.Open();
cmd.Connection = conn;
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Int32 Divide = (int)rdr["Divide"];
double Calc = (double)rdr["Calc"];
int HW = Convert.ToInt32(length_txt.Text);
foreach (GridViewRow row in GridViewAMI.Rows)
{
string Length = ((Label)row.FindControl("Length")).Text;
Response.Write(Length);
Length = ((HW / Divide) - Calc).ToString();
}
}
rdr.Close();
cmd.Dispose();
conn.Close();
}

Since I can't see you populating the Label again maybe this helps:
foreach (GridViewRow row in GridViewAMI.Rows)
{
// Get the Label safely so you can manipulate it later
Label rowLabel = row.FindControl("Length") as Label;
// If you - for whatever reason - can't get the Label, skip this row
if(rowlabel == null)
continue;
string length = rowLabel.Text;
Response.Write(length);
length = ((HW / Divide) - Calc).ToString();
// Populate the Label with the new Data
rowLabel.Text = length;
}

Try this:
foreach (GridViewRow row in GridViewAMI.Rows)
{
Label lbl = (Label)row.FindControl("Length");
string length = lbl.Text;
Response.Write(length);
length = ((HW / Divide) - Calc).ToString();
lbl.Text = length;
}
You forgot to put the text back in the Label.

Related

Changing Label Text line depending on Length in C#

So I am developing an application in WinForms and I am populating data from an Access database into a Combobox. After populating it I will use the items from the Combobox to display data on my labels. This is what I have to populate data:
public void AutoCompleteBrand()
{
OleDbConnection con = new OleDbConnection(cs.DBConn);
con.Open();
adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand(#"SELECT DISTINCT RTRIM(Phone) FROM tblPhone", con);
ds = new DataSet("ds");
adapter.Fill(ds);
dtable = ds.Tables[0];
cmbPhone.Items.Clear();
foreach (DataRow drow in dtable.Rows)
{
cmbPhone.Items.Add(drow[0].ToString());
}
}
Then inside of Combobox selected index event I will use this code:
private void cmbPhone_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
OleDbConnection con = new OleDbConnection(cs.DBConn);
con.Open();
cmd = new OleDbCommand(#"SELECT DISTINCT
Brand, Phone, Tecnology
FROM tblPhone", con);
OleDbDataAdapter mAdapter = new OleDbDataAdapter(cmd);
DataSet mDataSet = new DataSet();
OleDbDataReader mReader;
mReader = cmd.ExecuteReader();
while (mReader.Read())
{
string sBrand = mReader.GetString(0);
string sPhone = mReader.GetString(1);
string sTec = mReader.GetString(2);
lblBrand.Text = sBrand;
lblPhone.Text = sPhone;
lblTec.Text = sTec;
}
}
catch (Exception ex)
{
MessageBox.Show("Erro\nDetalhes: " + ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Basically the technology label is too big and when it reaches a length changes line. It is doable?
you just need to set two properties to your label: AutoSize and MaximumSize. AutoSizetells label to grow (both horizontally and vertically) but MaximumSize limits it to certain Width and Height. So. just do something like this:
label1.AutoSize = true;
label1.MaximumSize = new Size(100, 600);
label1.Text = "test string which is pretty long";
Your question is not very clear. You are working with WPF or Winforms ?
Basicly you can try a few things like :
-If winforms, you can set the autosize property = true of your label.
you can try Something like this :
while (mReader.Read())
{
string sBrand = mReader.GetString(0);
string sPhone = mReader.GetString(1);
string sTec = mReader.GetString(2);
lblBrand.Text = sBrand;
lblPhone.Text = sPhone;
lblTec.Text = sTec;
int wdth = sTec.Length * 16; //you can put another value depending your charachter size.
lblTech.Size = new Size(wdth, 22);
}
Or if you can give a fix width to your label and you can check the length of your string to add a new line :
int lngth = 100;
if(sTech.Length > lngth)
{
sTech = sTech.SubString(0, lngth) + Environment.NewLine + sTech.SubString(lngth);
lblTech.Text = sTech;
}
Tell me if it works.

"OleDBException was unhandled. Data type mismatch in criteria expression." in AutoNumber (id). What to do?

I have this codes below, but I don't know what is the reason why it was always having errors. Here is the code:
private void btn_acart_Click(object sender, EventArgs e)
{
con.Open();
string[] product = new string[7];
string[] select = new string[2];
int[] num = new int[5];
foreach (ListViewItem item in listView1.SelectedItems)
{
select[1] = item.Text;
string str = "SELECT * FROM [lblProduct] WHERE [prod_id]='"+select[1]+"'";
com = new OleDbCommand(str, con);
read = com.ExecuteReader();
while (read.Read())
{
product[1] = (read["prod_id"].ToString());
product[2] = (read["prod_name"].ToString());
product[3] = (read["prod_price"].ToString());
product[4] = (read["prod_stock"].ToString());
this.listView2.Items.Add(new ListViewItem(new string[] { product[1], product[2], product[3], product[4] }));
cartitems++;
num[1] = int.Parse(product[4]);
num[2] = int.Parse(txt_items.Text);
string strg = "UPDATE lblProduct SET prod_stock='"+(num[1] - num[2]+"' WHERE prod_id='"+product[1]+"'");
com = new OleDbCommand(strg, con);
com.ExecuteNonQuery();
}
}
loaddbase();
con.Close();
txt_items.Text = "0";
}
}
What should I do? What should I change? Please help! The error is always repeating at the read = com.ExecuteReader();
Access Database:
Format: (Field Name - Data Type)
prod_id - AutoNumber
prod_name - Text
prod_price - Text
prod_stock - Text
Are there anything to change in the database?

How to Create a Sales Invoice Report in Crystal Report(Bind data in Two Table)

I need to create a crystal report to display data in two tables(ie,Sales_Invoice and Sales_Invoice_Items).Sales_Invoice_Items has a foreign from Sales_Invoice.I need to display report like this,
I am created a Crystal report to display data like this. Data in Sales_Invoice table is properly grouped with respect to invoice_no. But Its display all the data in Sales_Invoice_Items Tables in each Sales_Invoice row.I need to display Sales_Invoice_Items data with respect to Sales_Invoice's foreign in Sales_Invoice_Items
Then I am Bind it with following code.
private DataSet getData()
{
DataSetSalesReport ds = new DataSetSalesReport();
try
{
using (SqlConnection con = new SqlConnection(DBCon.conStr))
{
con.Open();
SqlCommand cmd = new SqlCommand(AppConstraints.GET_SALES_REPORT);
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader rd = cmd.ExecuteReader();
decimal slno = 1;
while (rd.Read())
{
DataRow dr = ds.Tables["DataTable1"].NewRow();
dr["Id"] = rd["Id"].ToString();
dr["invoiceno"] = rd["invoiceno"].ToString();
dr["invoice_date"] = rd["invoice_date"].ToString();
dr["delivery_date"] = rd["delivery_date"].ToString();
dr["account"] = rd["account"].ToString();
dr["customer"] = rd["customer"].ToString();
dr["gross_amount"] = rd["gross_amount"].ToString();
dr["discount"] = rd["discount"].ToString();
dr["total_tax"] = rd["total_tax"].ToString();
dr["net_amount"] = rd["net_amount"].ToString();
dr["cash_discount"] = rd["cash_discount"].ToString();
dr["freight_charge"] = rd["freight_charge"].ToString();
dr["additional"] = rd["additional"].ToString();
dr["paid"] = rd["paid"].ToString();
dr["balance"] = rd["balance"].ToString();
dr["balancepaid_date"] = rd["balancepaid_date"].ToString();
dr["note"] = rd["note"].ToString();
dr["total_amount"] = rd["total_amount"].ToString();
dr["payment_mode"] = rd["payment_mode"].ToString();
dr["ac"] = rd["ac"].ToString();
dr["reg_date"] = rd["reg_date"].ToString();
dr["last_update"] = rd["last_update"].ToString();
dr["invoice_note"] = rd["invoice_note"].ToString();
dr["slno"] = slno++.ToString();
ds.Tables["DataTable1"].Rows.Add(dr);
using (SqlConnection con1 = new SqlConnection(DBCon.conStr))
{
con1.Open();
SqlCommand cmd1 = new SqlCommand(AppConstraints.GET_SALES_ITEMS_REPORT);
cmd1.Connection = con1;
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#Id", rd["Id"].ToString());
SqlDataReader rd1 = cmd1.ExecuteReader();
decimal j = 1;
while(rd1.Read())
{
DataRow dr1 = ds.Tables["DataTable2"].NewRow();
dr1["Id"] = rd1["Id"].ToString();
dr1["invoice_id"] = rd["Id"].ToString();
dr1["item_name"] = rd1["item_name"].ToString();
dr1["barcode"] = rd1["barcode"].ToString();
dr1["rate"] = rd1["rate"].ToString();
dr1["discount"] = rd1["discount"].ToString();
dr1["qty"] = rd1["qty"].ToString();
dr1["unit"] = rd1["unit"].ToString();
dr1["tax"] = rd1["tax"].ToString();
dr1["net"] = rd1["net"].ToString();
dr1["mrp"] = rd1["mrp"].ToString();
dr1["slno"] = j++.ToString();
ds.Tables["DataTable2"].Rows.Add(dr1);
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return ds;
}
The I am call above method in Window_Loaded event in WPF Window
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ReportDocument report = new ReportDocument();
report.Load("rptSalesReport.rpt");
report.SetDataSource(getData());
PrintSalesReport.ViewerCore.ReportSource = report;
PrintSalesReport.ToggleSidePanel = SAPBusinessObjects.WPF.Viewer.Constants.SidePanelKind.None;
}
My DataSet is shown below
After Running it i got the following result
In above result; it display all the Sales_invoice_Items data below in each of Sales_Invoice Data.
I need to display Sales_Invoice Data with respect its Sales_Invoice_Items Data(Sales_Invoice_Items contains Sales_Invoice's foreign key).I need your help to do this.
Thank You
Use Sub Report to solve this problem

Changing Quantity value within Datagridview, the price also changes. how possible? which event will do this.CellEndEdit already used

I want to Change Quantity value within Datagridview, it will change price also. how it is possible? which event is for it using C# windows form.CellEndEdit already used by other cell(productname).
private void dataGridViewSalesForm_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
try
{
string MatchingProduct = dataGridViewSalesForm.Rows[0].Cells[1].Value.ToString();
for (int i = 0; i < objArrayList.Count; i++)
{
if (objArrayList[i].ToString().ToLower().StartsWith(MatchingProduct.ToLower()))
{
dataGridViewSalesForm.Rows[0].Cells[1].Value = objArrayList[i].ToString();
break;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
/*connection for loading brandname from brandtable*/
string get_strProductName = dataGridViewSalesForm.Rows[0].Cells[1].Value.ToString();
string quantity = "1";
SqlConnection conn = new SqlConnection(connstr);
try
{
conn.Open();
string qry = "SELECT T_Inv_Brands.brand_name FROM T_Inv_Products INNER JOIN T_Inv_Brands ON T_Inv_Products.brand_id = T_Inv_Brands.brand_id WHERE T_Inv_Products.prod_name ='" + get_strProductName + "'";
SqlCommand cmd = new SqlCommand(qry, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridViewSalesForm.Rows[0].Cells[2].Value = ds.Tables[0].Rows[0]["brand_name"].ToString();
dataGridViewSalesForm.Rows[0].Cells[3].Value = quantity;
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
/*connection for loading retailprice from producttable*/
SqlConnection connection = new SqlConnection(connstr);
try
{
conn.Open();
string qry = "SELECT retailprice FROM T_Inv_Products WHERE prod_name = '" + get_strProductName + "'";
SqlCommand cmd = new SqlCommand(qry, connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridViewSalesForm.Rows[0].Cells[4].Value = Convert.ToDouble(dt.Rows[0]["retailprice"].ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
//double quantityload = Convert.ToDouble(dataGridViewSalesForm.Rows[0].Cells[3].Value.ToString());
//double pricefetch = Convert.ToDouble(dataGridViewSalesForm.Rows[0].Cells[4].Value.ToString());
//double result = quantityload * pricefetch;
//dataGridViewSalesForm.Rows[0].Cells[4].Value = result.ToString();
}
You seem to think that you can use an event for one cell or column only. Instead you need to code your events in such a way that all necessary cells and/or columns get their own piece of logic.
It helps to partition your code into smaller pieces with helpful names that document the logic they contain!
Here is an example with two branches, one for a certain cell and one for a certain column. I pass out the DataGridViewCellEventArgs so the functions can access the DataGridView DGV just as the real event can.. Of course you can expand on it as needed:
int quantityColumnIndex = 3; // use your own numbers..
int currencyColumnIndex = 1; // ..and names!!
int currencyRowIndex = 0;
int pricePerUnitColumnIndex = 7;
int totalPriceColumnIndex = 8;
int totalBasePriceColumnIndex = 4;
private void DGV_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == quantityColumnIndex) doPriceCalc(e);
else if (e.ColumnIndex == currencyColumnIndex && e.RowIndex == currencyRowIndex)
doAllCalc(e);
}
void doPriceCalc(DataGridViewCellEventArgs e)
{
// 1st example
DGV[totalPriceColumnIndex, e.RowIndex].Value =
(int)DGV[quantityColumnIndex, e.RowIndex].Value *
(decimal)DGV[pricePerUnitColumnIndex, e.RowIndex].Value;
}
void doAllCalc(DataGridViewCellEventArgs e)
{
// 2nd example
decimal currency = (decimal) DGV[currencyColumnIndex,currencyRowIndex ].Value;
for (int row = 0; row < DGV.Rows.Count; row++)
DGV[pricePerUnitColumnIndex, e.RowIndex].Value =
(decimal)DGV[totalBasePriceColumnIndex, e.RowIndex].Value * currency;
}
Note that I have indexed the columns by their indeices. You may just as well index them by their names, e.g.: DGV[ "PricePerUnit", e.rowIndex]

Search string value from string array, if conditional then get sql database and display gridview or else show error

I have tried several ways to do this but some reason I am not able to correctly implement the If statement.
I am trying to acquire the SelectedItem.Text from Drop Down List and then search in the database for that row and store it in DataSet and then display it on a GridView. However, the database has 19 fixed columns with words, so if the user selects one drop down listing in the if statement the DataSet should get displayed on a GridView but if the data is not found in the database Else an error message should pop up saying "Data Not Found"
I have tried physically inputting the 19 fixed columns in an Array and using the following:
protected void SearchProductButton_Click1(object sender, EventArgs e)
{
string Producttext = SearchProductDropDownList.SelectedItem.Text;
string[] Producttext2 =
{
"Chem",
"Drill",
"Elect",
"Products",
"Environmental",
"Instrument",
"Lab",
"Lift",
"Tools",
"Repair",
"Pipes",
"Portable",
"Power",
"Steel",
"Testing",
"Tooling",
"Tubes",
"Valves",
"Systems",
"Consumables",
};
using (var con = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True"))
using (var daProduct = new SqlDataAdapter("SELECT [Serial_No], [Material_No], [Product_Line], [Product_Description], [Size], [UOM], [Supplier_Price], [Price_Date], [Selling_Price] FROM [ProductDB] WHERE [Product_Line] = #Product_Line", con))
{
foreach (string x in Producttext2)
{
if (x.Contains(Producttext))
{
daProduct.SelectCommand.Parameters.Add("#Product_Line", SqlDbType.VarChar, 50).Value = Producttext;
DataSet dsProduct = new DataSet();
daProduct.Fill(dsProduct, "Product_Line");
SearchProductGridView.DataSource = dsProduct;
SearchProductGridView.DataBind();
}
else
{
MessageBox.Show("Data Not Found");
}
}
}
}
In the SQL data I only have information filled for Chem & Elect so all the other ones should show an error but due to the Foreach the xvalue` is not clearing and stays at the first run value so it ends up skipping until it goes through the whole list.
I have modified the code after reading about the string to string array and then checking the index if it is greater then -1 continue or else show the error.
Here's the code:
protected void SearchProductButton_Click1(object sender, EventArgs e)
{
string Producttext = SearchProductDropDownList.SelectedItem.Text;
string[] Productarray = new string[20];
Productarray[0] = "Chem";
Productarray[1] = "Drill";
Productarray[2] = "Elect";
Productarray[3] = "Products";
Productarray[4] = "Environmental";
Productarray[5] = "Instrument";
Productarray[6] = "Lab";
Productarray[7] = "Lift";
Productarray[8] = "Tools";
Productarray[9] = "Repair";
Productarray[10] = "Pipes";
Productarray[11] = "Portable";
Productarray[12] = "Power";
Productarray[13] = "Steel";
Productarray[14] = "Testing";
Productarray[15] = "Tooling";
Productarray[16] = "Tubes";
Productarray[17] = "Valves";
Productarray[18] = "Systems";
Productarray[19] = "Consumables";
using (var con = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True"))
using (var daProduct = new SqlDataAdapter("SELECT [Serial_No], [Material_No], [Product_Line], [Product_Description], [Size], [UOM], [Supplier_Price], [Price_Date], [Selling_Price] FROM [ProductDB] WHERE [Product_Line] = #Product_Line", con))
{
//foreach (string x in Producttext2)
//{
int index1 = Array.IndexOf(Productarray, Producttext);
if (index1 !=-1)
{
daProduct.SelectCommand.Parameters.Add("#Product_Line", SqlDbType.VarChar, 50).Value = Producttext;
DataSet dsProduct = new DataSet();
daProduct.Fill(dsProduct, "Product_Line");
SearchProductGridView.DataSource = dsProduct;
SearchProductGridView.DataBind();
}
else
{
MessageBox.Show("Data Not Found");
}
//}
}
}
The problem with the second approach is that it never goes to the else statement no matter what I try.
Edit:
I have decided to approach my requirement in a different way, instead of using Textbox I have sorted to using ComboBox from AJAX ToolKit.
Here's the HTML:
<ajaxToolkit:ComboBox ID="SearchMaterialComboBox" runat="server"
AutoCompleteMode="Append" AutoPostBack="false" CaseSensitive="false"
DataSourceID="ProductDBMaterialSqlDataSource" DataTextField="Material_No"
DataValueField="Material_No" DropDownStyle="DropDownList" Height="20px"
MaxLength="10" RenderMode="Block" style="display: inline-block;" Width="285px">
</ajaxToolkit:ComboBox>**strong text**
Code:
protected void SearchMaterialButton_Click(object sender, EventArgs e)
{
//long Materialtextbox = Convert.ToInt64(SearchMaterialComboBox.Text);
string Materialstr = SearchMaterialComboBox.Text;
using (var con = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True"))
using (var daMaterial = new SqlDataAdapter("SELECT [Serial_No], [Material_No], [Product_Line], [Product_Description], [Size], [UOM], [Supplier_Price], [Price_Date], [Selling_Price] FROM [ProductDB] WHERE [Material_No] = #Material_No", con))
{
if (Materialstr != "")
{
daMaterial.SelectCommand.Parameters.Add("#Material_No", SqlDbType.BigInt).Value = Materialstr;
DataSet dsMaterial = new DataSet();
daMaterial.Fill(dsMaterial, "Material_No");
SearchProductGridView.DataSource = dsMaterial;
SearchProductGridView.DataBind();
}
else
{
}
}
}
I believe the last post mentioned by #Patashu had a valid point by inserting in the HasRows a value of 0, if it is not 0 then continue else show an error message. However, the current approach has the AutoComplete option which is neat comparing to the conventional TextBox approach.
using System.Linq;
string match = Producttext2.FirstOrDefault((x) => x.Contains(Producttext));
if (match != null)
{
// do stuff
}
else
{
// error message
}
Method from http://msdn.microsoft.com/en-us/library/bb549039.aspx

Categories