Can't get the total row count - c#

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

Related

How to refresh tablelayoutpanel contents in user control on button click

I have a button click event in one user control that will deduct 1 from the stock of ingredients in tbl_ingredients whenever it matches the ingredient found in string array ings.
private void btn_confirm_Click(object sender, EventArgs e, string[] ings)
{
foreach (string s in ings)
{
string qry = "UPDATE tbl_ingredients SET inv_stock = inv_stock -1 WHERE inv_name = '" + s + "'";
SQLiteCommand myCommand = new SQLiteCommand(qry, myConnection);
myCommand.ExecuteNonQuery();
}
}
and a dynamically created tablelayoutpanel (to display all the ingredients and their respective total stock) in another user control
myConnection = new SQLiteConnection("Data Source=database.sqlite3");
string qry = "SELECT * FROM tbl_ingredients ORDER BY inv_name";
string qry2 = "SELECT COUNT(*) FROM tbl_ingredients";
SQLiteCommand myCommand = new SQLiteCommand(qry, myConnection);
SQLiteCommand myCommand2 = new SQLiteCommand(qry2, myConnection);
openConnection();
int row = Convert.ToInt32(myCommand2.ExecuteScalar());
SQLiteDataReader result = myCommand.ExecuteReader();
string[] itemname = new string[row];
string[] totalstock = new string[row];
int cnt = 0;
if (result.HasRows)
{
while (result.Read())
{
itemname[cnt] = result["inv_name"].ToString();
totalstock[cnt] = result["inv_stock"].ToString();
cnt++;
}
}
//tlb_inventory is the name of the tablelayoutpanel in windows form
tbl_inventory.ColumnCount = 2;
tbl_inventory.RowCount = row;
tbl_inventory.Controls.Add(new Label() { Text = "Item" }, 0, 0);
tbl_inventory.Controls.Add(new Label() { Text = "Total Stock" }, 1, 0);
for (int i = 1, j = 0; i < row + 1; i++, j++)
{
tbl_inventory.Controls.Add(new Label() { Text = itemname[j], AutoSize = true }, 0, i);
tbl_inventory.Controls.Add(new Label() { Text = totalstock[j], AutoSize = true }, 1, i);
}
closeConnection();
Whenever I click on the button, it should update the contents of the table in real-time. The issue is that I have to re-run the program in order for it to display the updated contents of the table. Is there a function or something that will make the user control and its contents refresh after button click?
First you need to set the name property to the labels control
tbl_inventory.Controls.Add(new Label() { Name = "Total_"+ itemname[j], Text = totalstock[j], AutoSize = true }, 1, i);
and then at the button_click event inside foreach loop add:
Label c = (tbl_inventory.Controls.Find("Total_" + s, true).First() as Label);
var total = Convert.ToInt32(c.Text);
c.Text = (total++).ToString();

Display rows retrieved from a database in seperate textboxes

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);

Convert Rank to percentage C#

I am trying to display percentage based on the rank of each record returned in search. I want it to loop through each item but it only loops through the first item as many times as I have items. For instance if it found 4 results it would display the rank of the first one on all 4 results.
Any suggestions to get it to display each rank separately and convert it to percentage?
private void BindRpt()
{
if (string.IsNullOrEmpty(txtSearch.Text)) return;
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString);
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.CommandText = "select Distinct Rank, SUBSTRING(ColumnA, 1, 500) AS ColumnA, ColumnB, ColumnC, ColumnD, ColumnE from FREETEXTTABLE (TABLE , ColumnA, '" + Search.Text + "' ) S, TABLE C WHERE c.ID = S.[KEY] order by Rank Desc";
DataTable dt = new DataTable();
adapter.SelectCommand = cmd;
adapter.Fill(dt);
PagedDataSource pgitems = new PagedDataSource();
pgitems.DataSource = dt.DefaultView;
pgitems.AllowPaging = true;
pgitems.PageSize = 3;
pgitems.CurrentPageIndex = PageNumber;
if (pgitems.Count > 1)
{
rptPaging.Visible = true;
ArrayList pages = new ArrayList();
for (int i = 0; i <= pgitems.PageCount - 1; i++)
{
pages.Add((i + 1).ToString());
}
rptPaging.DataSource = pages;
rptPaging.DataBind();
lblSentence.Visible = true;
lblSearchWord.Visible = true;
lblSearchWord.Text = txtSearch.Text;
}
else
{
rptPaging.Visible = false;
lblSentence.Visible = true;
lblSentence.Text = "Results were found for";
lblSearchWord.Visible = true;
lblSearchWord.Text = txtSearch.Text;
}
rptResults.DataSource = pgitems;
rptResults.DataBind();
cn.Close();
}
protected void rptResults_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["HTAA"].ConnectionString);
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.CommandText = "select Distinct Rank, SUBSTRING(ColumnA, 1, 500) AS ColumnA, ColumnB, ColumnC, ColumnD, ColumnE from FREETEXTTABLE (TABLE , ColumnA, '" + Search.Text + "' ) S, TABLE C WHERE c.ID = S.[KEY] order by Rank Desc";
int number = Page.Items.Count;
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
int firstrank = dr.GetInt32(0);
while (dr.Read())
{
int rank = dr.GetInt32(0);
int percentage = (rank / firstrank) * 100;
Label lblpre = (Label)e.Item.FindControl("lblRank");
lblpre.Text = percentage.ToString();
}
}
dr.Close();
cn.Close();
}
After a chat, I have a better handle on things. A way to do this;
Create a private field on your code behind file.
private int topRanked = 0;
In your Bind method()
private void Bind()
{
...
DataTable dt = new DataTable();
adapter.SelectCommand = cmd;
adapter.Fill(dt);
topRanked = (int)dt.Rows[0]["Rank"];
Now, make your OnItemDataBound method;
protected void OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
var dataItem = e.Item.DataItem as DataRowView;
int rank = (int) dataItem["Rank"];
var percentage = ((double)topRanked / rank) * 100;
Label label = (Label)e.Item.FindControl("labelRank");
label.Text = percentage.ToString();
}
as mentioned. I don't believe it's the best answer, but it is an answer. I'm sure a stored procedure, or even a better sql method could probably calculate this and not leave you making calculations in code.
Can you try with while(dr.Read()) instead of "if"?
You will want to loop over the result set
while (dr.Read())
{
int rank = dr.GetInt32(0);
int percentage = (rank / rank) * 100;
Label lblpre = (Label)e.Item.FindControl("lblRank");
lblpre.Text = rank.ToString();
}
"but it only loops through the first item" - because you have a for and checks for i <= 0
for (int i = 0; i <= 0; i++)
{
....
}
You just don't need this for statement but rather use
if (dr != null)
using (dr)
{
while (dr.Read())
{
..
}
}
It's always better to use using when dealing with db connection objects so the resources used by these objects are properly disposed after it's been used.

How to pass multiple selected item text from DropDownListCheckBoxes to Parameterized Sql

I am able to retain the DropDownListCheckbox multi-selected items text inside a label with a button click. I need to search from the database based on the DropDownListCheckBox multi selected items and its related data from a SQL-Server database.
How to achieve the search option using a button click by passing the input from DDL_CB list items or label text to parameterized SQL query?
My requirement: the search feature must display the data in JQgrid based on the text contained in the Label or DDL_CheckBox multi-selected items.
My C# code:
static string value1;
static string value2;
static string value3;
protected void createmaincontrols()
{
//Create a Dynamic Panel
DynamicPanel = new Panel();
DynamicPanel.ID = "DynamicPanel";
DynamicPanel.Width = 1600;
//Create Main Table
var dynamic_filter_table = new WebForms.Table();
dynamic_filter_table.ID = "dynamic_filter_table_id";
TableRow campaign_table_row = new TableRow();
campaign_table_row.ID = "country_table_row";
TableRow campaign_label_row = new TableRow();
campaign_label_row.ID = "country_label_row";
TableCell campaignnamecell = new TableCell();
campaignnamecell.ID = "countrynamecell";
TableCell btncell = new TableCell();
btncell.ID = "btncell";
TableCell labelcell = new TableCell();
labelcell.ID = "labelcell";
//Create Campaigns DDL
DropDownCheckBoxes DDL_checkbox = new DropDownCheckBoxes();
DDL_checkbox.ID = "MainDDL_Countries";
DDL_checkbox.AutoPostBack = true;
DDL_checkbox.ForeColor = System.Drawing.Color.MidnightBlue;
DDL_checkbox.Font.Size = FontUnit.Point(8);
DDL_checkbox.Font.Bold = true;
DDL_checkbox.Font.Name = "Arial";
DDL_checkbox.AddJQueryReference = true;
DDL_checkbox.UseButtons = true;
DDL_checkbox.UseSelectAllNode = true;
DDL_checkbox.Style.SelectBoxWidth = 200;
DDL_checkbox.Style.DropDownBoxBoxWidth = 200;
DDL_checkbox.Style.DropDownBoxBoxHeight = 130;
DDL_checkbox.Texts.SelectBoxCaption = "Select Countries";
DDL_checkbox.Items.Add(new ListItem("SINGAPORE"));
DDL_checkbox.Items.Add(new ListItem("UNITED KINGDOM"));
DDL_checkbox.Items.Add(new ListItem("MALAYSIA"));
DDL_checkbox.Items.Add(new ListItem("INDIA"));
DDL_checkbox.Items.Add(new ListItem("FRANCE"));
DDL_checkbox.Items.Add(new ListItem("GERMANY"));
DDL_checkbox.Items.Add(new ListItem("NORWAY"));
DDL_checkbox.DataTextField = "Country Name";
DDL_checkbox.DataBind();
DDL_checkbox.AutoPostBack = true;
DDL_checkbox.EnableViewState = false;
Button submitbutton = new Button();
submitbutton.ID = "mybutton";
submitbutton.Text = "SubmitSelectedCountries";
submitbutton.Click += new EventHandler(Buttonnew_Click);
submitbutton.Font.Name = "Arial";
submitbutton.Font.Bold = true;
submitbutton.Font.Size = FontUnit.Point(8);
submitbutton.ForeColor = System.Drawing.Color.MidnightBlue;
submitbutton.BackColor = System.Drawing.Color.LightGray;
submitbutton.UseSubmitBehavior = false;
Label lblCampaignName = new Label();
lblCampaignName.ID = "Countries";
lblCampaignName.Font.Bold = true;
lblCampaignName.Font.Size = FontUnit.Point(8);
lblCampaignName.ForeColor = System.Drawing.Color.MidnightBlue;
lblCampaignName.BackColor = System.Drawing.Color.LightGray;
campaignnamecell.Controls.Add(DDL_checkbox);
campaignnamecell.Controls.Add(submitbutton);
campaignnamecell.Controls.Add(lblcountryname);
campaign_table_row.Controls.Add(countrycell);
dynamic_filter_table.Controls.Add(country_table_row);
DynamicPanel.Controls.Add(dynamic_filter_table);
SelectPanel.Controls.Add(DynamicPanel);
}
C# code to retrieve the dropdown checked items in a label using a button click
protected void Buttonnew_Click(object sender, EventArgs e)
{
Table maintable = Select.FindControl("dynamic_filter_table_id") as Table;
DropDownCheckBoxes DDL_checkbox = maintable.FindControl("MainDDL_Contries") as DropDownCheckBoxes;
Label lblcountryname = maintable.FindControl("Country") as Label;
List<String> Country_List = new List<string>();
foreach (System.Web.UI.WebControls.ListItem item in DDL_checkbox.Items)
{
if (item.Selected)
{
Country_List.Add(item.Text);
}
lblcountryname .Text = String.Join(",", Country_List.ToArray());
}
}
How to search the country details based on a parameterized SQL query input from label or dropdowncheckbox selected items?
protected void Button4_Click(object sender, EventArgs e)
{
Table maintable = Select.FindControl("dynamic_filter_table_id") as Table;
int rc = maintable.Rows.Count;
if (rc == 2)
{
//Three country selected in DDL_checkbox
DropDownCheckBoxes d4 = maintable.FindControl("MainDDL_Countries") as DropDownCheckBoxes;
Label lblcountryname = maintable.FindControl("Countries") as Label;
var countryname= test.ToString().Split(new[] { ',', '\n' }).ToArray();
if(countryname.Count() >=1 && countryname.Count() <=3)
{
value1 = countryname.ElementAt(0).ToString();
value2 = countryname.ElementAt(1).ToString();
value3 = countryname.ElementAt(2).ToString();
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT C.Country_Name,C.Address FROM COUNTRYTABLE as C WHERE C.Country_Name in(#t4,#t5,#t6)";
cmd.Parameters.Add("#t4", SqlDbType.VarChar).Value = value1;
cmd.Parameters.Add("#t5", SqlDbType.VarChar).Value = value2;
cmd.Parameters.Add("#t6", SqlDbType.VarChar).Value = value3;
con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter sql = new SqlDataAdapter(cmd);
DataSet data = new DataSet();
sql.Fill(data);
con.Close();
Session["DataforSearch_DDL"] = data.Tables[0];
}
}
This is admittedly a partial answer. It will get you started.
When you submit a form with multi-selected items, the selected items are passed as comma separated values. Something like this:
value1,value2,etc
You want your query to have a where clause like this:
where someTextfield in ('value1','value2','etc')
or without the quotes for numeric fields. However, you wisely said that you wanted to use parameters.
Here endeth the partial answer.
long-long time ago, I used to do it this way:
for (int i = 0; i < param.Length; i++)
if (param[i] != "" && param[i] != null)
s_comm.Parameters.AddWithValue(tParam + i.ToString(), param[i]);
where:
private string tParam = "#Param";
string[] paramName // Name of the parameters
string[] param // Values for those parameters.
and I was building a statement like this:
string where = "";
if (paramName != null)
for (int i = 0; i < paramName.Length; i++)
if (paramName[i] != "" && paramName[i] != null)
if (i == 0)
where = " WHERE " + paramName[i] + " = " + tParam + i.ToString();
else
where += ", " + paramName[i] + " = " + tParam + i.ToString();
else throw new Exception(noColumnName + " at position #:" + i.ToString());
else where = "";
if (table != "") return "SELECT * FROM " + table + where;
I am sure there are more elegant solutions, but this is a start, right?

where I am wrong? creating labels dynamically c#

I created labels and textboxes dynamically . everything goes fine,but the second label doesn't want to appear at all. where i am wrong? this is my code in C#:
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
OracleDataReader reader;
int x = 434;
int y = 84;
int i = 0;
try
{
conn.Open();
foreach (var itemChecked in checkedListBox1.CheckedItems)
{
Label NewLabel = new Label();
NewLabel.Location = new Point(x + 100, y);
NewLabel.Name = "Label" + i.ToString();
Controls.Add(NewLabel);
TextBox tb = new TextBox();
tb.Location = new Point(x, y);
tb.Name = "txtBox" + i.ToString();
Controls.Add(tb);
y += 30;
OracleCommand cmd = new OracleCommand("SELECT distinct data_type from all_arguments where owner='HR' and argument_name='" + itemChecked.ToString() + "'", conn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
label[0].Text = reader["data_type"].ToString();
}
i++;
}
}
finally
{
if (conn != null)
conn.Close();
}
}
private void Procedure()
{
string proc = "";
try
{
conn.Open();
if (this.listView1.SelectedItems.Count > 0)
proc = listView1.SelectedItems[0].Text;
OracleCommand cmd = new OracleCommand("" + proc + "", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
int i = 0;
foreach (var itemChecked1 in checkedListBox1.Items)
{
Control[] txt = Controls.Find("txtBox" + i.ToString(), false);
Control[] label = Controls.Find("Label" + i.ToString(), false);
cmd.Parameters.Add(new OracleParameter("select distinct data_type from all_arguments where owner='HR' and argument_name=toupper("+itemChecked1.ToString()+")",conn));
cmd.Parameters[":"+itemChecked1.ToString()+""].Value=label[0].Text;
cmd.Parameters.Add(new OracleParameter(":" + itemChecked1.ToString() + "", OracleDbType.Varchar2));
cmd.Parameters[":" + itemChecked1.ToString() + ""].Value = txt[0].Text;
i++;
I think the second Label has appeared. But its text is an empty string! So you will never see it.
Check the "data_type" returned by DB reader.

Categories

Resources