How to get controls from panel in asp.net c#? - c#

Well, I am doing a project on online movie ticket booking.
My problem is, I want to show the seating arrangement in a screen of a particular theater.
As in every row the number of seats can vary so what I have done is add a panel and in it a checkboxlist is dynamically added during runtime.
each checkboxlist represents a single row.
string s;
for (int i = 0; i < ds.Tables["row_id_no_of_seats"].Rows.Count; i++)
{
cbl = new CheckBoxList();
cbl.RepeatDirection = 0; //horizontal
cbl.RepeatLayout = 0; //table
cbl.RepeatColumns = (int)ds.Tables["row_id_no_of_seats"].Rows[i].ItemArray[1];
Panel1.Controls.Add(cbl);
for(int j=1;j<=(int)ds.Tables["row_id_no_of_seats"].Rows[i].ItemArray[1];j++)
{
s = ds.Tables["row_id_no_of_seats"].Rows[i].ItemArray[0].ToString() + j.ToString(); //ex:A+1
cbl.Items.Add(s);
string query1 = "select booking_detail.row_id,booking_detail.column_id from booking_detail,booking where (booking_detail.booking_id=booking.booking_id) and (booking_detail.booking_date='" + bk_date + "') and (booking.booking_date='" + bk_date + "') and (booking.theatre_id=" + theatre_id + ") and (booking.screen_id=" + screen_id + ") and (booking.movie_id=" + movie_id + ") and (booking.show_start_time='" + show_start_time + "') and (booking.class_id=" + class_id + ")";
SqlCommand command1 = new SqlCommand(query1, connection);
adapter.SelectCommand = command1;
adapter.Fill(ds, "seat_booked_info");
// it checks and disables the seats which have been pre- booked.
for (int k = 0; k < ds.Tables["seat_booked_info"].Rows.Count;k++) {
if(ds.Tables["seat_booked_info"].Rows[k].ItemArray[0].ToString().Equals(ds.Tables["row_id_no_of_seats"].Rows[i].ItemArray[0].ToString())) && (ds.Tables["seat_booked_info"].Rows[k].ItemArray[1].ToString().Equals(j.ToString())))
{
cbl.Items.FindByText(s).Selected=true;
cbl.Items.FindByText(s).Enabled = false;
}
}
ds.Tables["seat_booked_info"].Clear();
}
}
Now what I want is, how do I get the details of the checkbox which have been selected by the user as the checkboxlist are dynamically added to the panel?

You would use something like this:
foreach (Control c in Panel1.Controls)
{
CheckBoxList list = c as CheckBoxList;
if (c != null)
{
// Do something with the list
}
}

Related

Populate dynamically created textboxes with SQL query

I need to dynamically create controls and display some database values in them.
For now I did :
SqlCommand cmdBE = new SqlCommand("SELECT COUNT (type) FROM composants_test WHERE type = 'BE' AND codeArticlePF LIKE'%" + motcle + "%' ", con);
Int32 countBE = (Int32) cmdBE.ExecuteScalar();
Console.WriteLine("nb BE : " +countBE);
SqlCommand cmdBEName = new SqlCommand("SELECT codeArticleComposant FROM composants_test WHERE type = 'BE' AND codeArticlePF LIKE'%" + motcle + "%'", con);
SqlDataReader readerBE = cmdBEName.ExecuteReader();
if (readerBE.Read())
{
Console.WriteLine(readerBE["codeArticleComposant"].ToString());
int pointXBE = 20;
int pointYBE = 20;
panelBE.Controls.Clear();
panelBE.Focus();
for (int i = 0; i < countBE; i++)
{
TextBox textBoxBE = new TextBox();
Label labelBE = new Label();
textBoxBE.Name = "textBoxBE" + i;
textBoxBE.Text = readerBE["codeArticleComposant"].ToString();
textBoxBE.Location = new Point(pointXBE + 35, pointYBE);
textBoxBE.CharacterCasing = CharacterCasing.Upper;
textBoxBE.Width = 150;
labelBE.Text = "BE" + (i + 1).ToString() + " : ";
labelBE.Location = new Point(pointXBE, pointYBE);
panelBE.Controls.Add(textBoxBE);
panelBE.Controls.Add(labelBE);
panelBE.Show();
pointYBE += 30;
}
readerBE.Close();
}
My problem is that if several Controls are created, "readerBE["codeArticleComposant"].ToString()" does not change.
How can I make it loop on the different results that I need ?
You actually need to keep reading until all the records are being read using While loop, so change your if to While like:
int i =0; // use local variable for generating controls unique names
While(readerBE.Read())
{
//............
//........... your code here
TextBox textBoxBE = new TextBox();
Label labelBE = new Label();
textBoxBE.Name = "textBoxBE" + i;
textBoxBE.Text = readerBE["codeArticleComposant"].ToString();
textBoxBE.Location = new Point(pointXBE + 35, pointYBE);
textBoxBE.CharacterCasing = CharacterCasing.Upper;
textBoxBE.Width = 150;
labelBE.Text = "BE" + (i + 1).ToString() + " : ";
labelBE.Location = new Point(pointXBE, pointYBE);
panelBE.Controls.Add(textBoxBE);
panelBE.Controls.Add(labelBE);
panelBE.Show();
i++; // increment after each read
}

Wrong Data Is Inserted in Access Database with C#

I have a small problem regarding the Access Database when it has data inserted.
I have a button that inserts data when it's clicked. Here it is the code:
string[] read = File.ReadAllLines("Harta_Distantelor.txt");
string[] orase = { "Constanta", "Varna", "Burgas", "Istambul", "Kozlu", "Samsun", "Batumi", "Sokhumi", "Soci", "Anapa", "Yalta", "Sevastopol", "Odessa" };
OleDbCommand cmd;
for (int i = 0; i < read.Length; i++)
{
int j = 0;
string[] numbers = read[i].Split(' ');
while (j < read.Length)
{
//cmd = new OleDbCommand("UPDATE Distante SET ID_Port='" + (i + 1) + "', ID_Port_Destinatie='" + (j + 1) + "', Nume_Port_Destinatie='" + orase[j] + "' WHERE Distanta='" + numbers[j] + "' ", conn);
cmd = new OleDbCommand("INSERT INTO [Distante]([ID_Port], [ID_Port_Destinatie], [Nume_Port_Destinatie], [Distanta]) VALUES ('" + (i + 1).ToString() + "', '" + (j + 1).ToString() + "', '" + orase[j] + "', '" + numbers[j] + "')", conn);
cmd.ExecuteNonQuery();
j++;
}
}
The problem is that instead of having something like ID_Port=1, ID_Port_Destinatie=1, Nume_Port_Destinatie="Constanta", ID_Port=1, ID_Port_Destinatie=2, Nume_Port_Destinatie="Varna" and so on, I get this...
https://i.stack.imgur.com/OjMQm.png
The file "Harta_Distantelor.txt" is a matrix that has the distances, so that's why I tried to split every number from a line(string[] numbers = read[i].Split(' ');). I have to mention that [Distanta] data is correctly inserted, but the rest of the data is totally randomly inserted. I tried to figure out where the problem is, but I have no clue. Where is the mistake? What should I try to do in order to have the data showed correctly?
1.) Create a table called HartaDistantelor with columns for ID_Port, ID_Port_Destinatie, and Distanta
2.) Fill the table HartaDistantelor with your matrix values. You may be able to copy and paste directly into Access
3.) Create a table called Orase with columns for ID_Port and Nume_Port
4.) Fill the table Orase with the 13 values from your array. It should look like this:
1 Constanta
2 Varna
3 Burgas
4 ...
5.) Change your code:
OleDbCommand cmd;
for (int i = 0; i < 12; i++)
{
for (int j = 0; j < 12; j++)
{
cmd = new OleDbCommand("INSERT INTO Distante (ID_Port, ID_Port_Destinatie, Nume_Port_Destinatie, Distanta) SELECT " + (i + 1).ToString() + ", " + (j + 1).ToString() + ", o.Nume_Port, h.Distanta FROM Orase o JOIN HartaDistantelor h ON h.ID_Port = o.ID_Port WHERE h.ID_Port = i AND h.ID_Port_Destinatie = j", conn);
cmd.ExecuteNonQuery();
}
}
My approach joins records from two tables using ID values that match. I don't think you made any mistake, but used a method with more complexity than was necessary.

If ELSE condition not working properly

I have a Multiple Select DROPDOWNLIST to select items. See the Dropdownlist below
[![dropdownlist][1]][1]
What I am doing is, I am selecting 2 items from the list. One of PROCESSED and another of PENDING
So what's happening wrong here is, when the condition is PROCESSED it works properly and goes in IF condition but second time it is PENDING but still it goes in the IF condition.
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
using (SqlCommand sqcmd = new SqlCommand("select month(a.dt_of_leave)month, year(a.dt_of_leave)year " +
"from emp_mst a where month(a.dt_of_leave) >= month(getdate())-1 and " +
"year(a.dt_of_leave)= case when month(getdate())=1 " +
"then year(getdate())-1 else year(getdate()) end " +
"and emp_card_no IN (" + str_emp_sel + ") order by emp_name", conn))
{
SqlDataAdapter damonthyear = new SqlDataAdapter(sqcmd);
damonthyear.Fill(dtspmonthyear);
for (i = 0; i < dtspmonthyear.Rows.Count; i++)
{
if (cmbEmp_Name.SelectedItem.Text.Contains("PROCESSED") == true)
{
//CF.ExecuteQuerry("exec Emp_Resign_Allocate_Leave '" + str_emp_sel + "','" + dtspmonthyear.Rows[0]["month"].ToString() + "', '" + dtspmonthyear.Rows[0]["year"].ToString() + "'");
}
else
{
// not going in else for `PENDING`
}
}
}
}
This is the markup:
<asp:DropDownCheckBoxes ID="cmbEmp_Name" AddJQueryReference="true" Width="60%" runat="server"
DataTextField="Employee Name" DataValueField="User_ID" UseSelectAllNode="false">
<Style DropDownBoxBoxWidth="500px" DropDownBoxBoxHeight="45%" SelectBoxWidth="55%" />
</asp:DropDownCheckBoxes>
try something similar to:
for (i = 0; i < dtspmonthyear.Rows.Count; i++)
{
foreach (var item in cmbEmp_Name.Items)
{
if (item.Selected)
{
if (item.Text.Contains("PROCESSED"))
{
//CF.ExecuteQuerry("exec Emp_Resign_Allocate_Leave '" + str_emp_sel + "','" + dtspmonthyear.Rows[0]["month"].ToString() + "', '" + dtspmonthyear.Rows[0]["year"].ToString() + "'");
}
else
{
// not going in else for `PENDING`
}
}
}
}
You apparently downloaded some control from the web. Its documentation states:
DropDownCheckBoxes is an ASP.NET server control directly inheriting from standard ASP.NET CheckBoxList control.
Cool, so we can just search the web for what we want to do: "ASP.NET CheckBoxList get selected items", which yields Q&As like How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart, How to get values of selected items in CheckBoxList with foreach in ASP.NET C#? and so on:
foreach (ListItem item in dropDownCheckBoxList.Items)
{
if (item.Selected)
{
// Do what you want to do
}
}

Sum of Gridview columns/rows ASP.NET C#

I want to make sums of columns and rows in a gridview , I tried so many ways and I can't do it. I'm trying to understand what's wrong. I'm sorry If my code is a mess. I'm using ASP.NET C#. For now it is enough to show sum only in a response.write, later i'll put it on a column/row.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=*****;Initial Catalog=***;User=***;password=**");
//query para o select das especialidades todas
string specstring = "SELECT Speciality.Shortname, SUM(1) as contar " +
"FROM DoctorEnterpriseDetails INNER JOIN " +
"Speciality ON DoctorEnterpriseDetails.Speciality1 = Speciality.SpecialityId INNER JOIN " +
" GroupType ON DoctorEnterpriseDetails.GroupId = GroupType.GroupId " +
" WHERE (DoctorEnterpriseDetails.EnterpriseId = 48) " +
" GROUP BY Speciality.Shortname ";
SqlCommand command = new SqlCommand(specstring, conn);
command.Connection.Open();
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
myDataAdapter.SelectCommand = command;
DataTable specstringtable = new DataTable();
myDataAdapter.Fill(specstringtable);
specstring = "";
for (int i = 0; i < specstringtable.Rows.Count; i++)
{
if (specstring == "")
{
specstring = "[" + specstringtable.Rows[i][0] + "]".ToString();
}
else
{
specstring = specstring + ", " + "[" + specstringtable.Rows[i][0] + "]";
}
}
command.Connection.Close();
////query para a pivot table
string querystring = "SELECT Description AS Categoria, " + specstring +
"FROM (SELECT GroupType.Description, Speciality.Shortname, SUM(1) AS contar, GroupType.GroupId " +
"FROM DoctorEnterpriseDetails INNER JOIN " +
"Speciality ON DoctorEnterpriseDetails.Speciality1 = Speciality.SpecialityId INNER JOIN " +
"GroupType ON DoctorEnterpriseDetails.GroupId = GroupType.GroupId " +
"WHERE (DoctorEnterpriseDetails.EnterpriseId = 48) " +
"GROUP BY GroupType.Description, Speciality.Shortname, DoctorEnterpriseDetails.GroupId, GroupType.GroupId) as ps " +
"PIVOT (SUM(contar) FOR Shortname IN (" + specstring + ")) pvt " +
"ORDER BY GroupId; ";
////Response.Write(querystring);
SqlCommand command2 = new SqlCommand(querystring, conn);
command2.Connection.Open();
SqlDataAdapter myDataAdapter2 = new SqlDataAdapter();
myDataAdapter2.SelectCommand = command2;
DataTable cobtable = new DataTable();
myDataAdapter2.Fill(cobtable);
DataColumn cl = cobtable.Columns.Add("Total");
cobtable.Columns["Total"].SetOrdinal(1);
DataRow dr;
dr = cobtable.NewRow();
dr["Categoria"] = "Total";
cobtable.Rows.InsertAt(dr, 0);
dr = cobtable.NewRow();
dr["Categoria"] = "";
cobtable.Rows.InsertAt(dr, 1);
dr = cobtable.NewRow();
dr["Categoria"] = "%";
cobtable.Rows.InsertAt(dr, 3);
dr = cobtable.NewRow();
dr["Categoria"] = "";
cobtable.Rows.InsertAt(dr, 4);
dr = cobtable.NewRow();
dr["Categoria"] = "%";
cobtable.Rows.InsertAt(dr, 6);
dr = cobtable.NewRow();
dr["Categoria"] = "";
cobtable.Rows.InsertAt(dr, 7);
dr = cobtable.NewRow();
dr["Categoria"] = "%";
cobtable.Rows.InsertAt(dr, 9);
GroupGrid.DataSource = cobtable;
GroupGrid.DataBind();
//GroupGrid.FooterRow.Cells[1].Text = cobtable.Compute("sum(" + cobtable.Columns[3].ColumnName + ")", null).ToString();
decimal a = 0, soma = 0;
string la = "";
//Response.Write(GroupGrid.Rows[0].Cells.Count);
for (int i = 3; i <= (GroupGrid.Rows[0].Cells.Count); i++)
{
Response.Write("!");
//string l3 = GroupGrid.Rows[6].Cells[i-1].Text;
// Response.Write(l3);
Response.Write(GroupGrid.Rows[5].Cells[i - 1].Text);
// la = GroupGrid.Rows[5].Cells[i - 1].Text;
// sum += Convert.ToInt32(la);
//sum = Convert.ToInt32(GroupGrid.Rows[5].Cells[i - 1].Text.ToString());
//a = a + sum;
//GroupGrid.FooterRow.Cells[1].Text = sum.ToString();
}
// Response.Write(a.ToString());
You are right your code is a little mess ;)
I tried to understand what you mean so just for a case here you have the example how to sum the values in row, sum the values in column or some both columns and rows so sum of all cells.
These examples assume you are not having cells spaning through more then one row or column and that the total sum of your values is less then "long" size and each cell contains number that is "integer".
public void DisplayGridViewSums(GridView gv)
{
foreach (GridViewRow row in gv.Rows)
{
long sum = SumValuesInRow(row);
Console.WriteLine("Sum of values in raw '{0}' is: {1}", row.RowIndex, sum);
}
for (int i=0; i<gv.Columns.Count;i++)
{
long sum = SumValuesInColumn(gv,i);
Console.WriteLine("Sum of values in column '{0}' with header '{1}' is: {2}",i, gv.Columns[i].HeaderText, sum);
}
long totalsum = SumColumnsAndRowsInGridView(gv);
Console.WriteLine("Sum of all cells in each row is: {0}", totalsum);
}
public long SumColumnsAndRowsInGridView(GridView gv)
{
long sum = 0;
foreach (GridViewRow row in gv.Rows)
{
sum += SumValuesInRow(row);
}
return sum;
}
public long SumValuesInRow(GridViewRow row)
{
long sum = 0;
foreach (TableCell cell in row.Cells)
{
sum += int.Parse(cell.Text);
}
return sum;
}
public long SumValuesInColumn(GridView gv, int columnIndx)
{
long sum = 0;
foreach (GridViewRow row in gv.Rows)
{
sum += int.Parse(row.Cells[columnIndx].Text);
}
return sum;
}
First method shows the sums on console. The other count the sums for particular GridView. Those counting methods could be written using Linq but for your convenience a left them as simple for and foreach loops.
Hope it solves your problem!

C# ListView index and column to string

I have a listview that has 2 columns and a checkbox.
What i'm doing is if the checkbox is true, I want to check the text from columns 1 and 2 and make it a string. This is what I have.
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Checked == true)
{
listView1.Items.RemoveAt(i);
string sql = "uscolumn = '" + listView1.Items[i].ToString() + "' and ukcolumn = '" + listView1.Items[i].ToString() + "'";
}
}
The above code doesn't work but i'm not sure which way to go with it, the .Check works as intended but the strings dont.
so in this example:
CheckBox|column1|Column2
True|Fruit|Apples
usColumn = "Fruit"
ulColumn = "Apples"
Here is my suggestion for you:
int i = 0;
while (i < listView1.Items.Count)
{
if (listView.Items[i].Checked)
{
string sql = "uscolumn = '" + listView1.Items[i].SubItems[0].Text + "' and ukcolumn = '" + listView1.Items[i].SubItems[1].Text + "'";
listView.Items.RemoveAt(i);
}
else
{
i++;
}
}
I think you need to use Items[i].Text rather than ToString():
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Checked == true)
{
listView1.Items.RemoveAt(i);
string sql = "uscolumn = '" + listView1.Items[i].Text + "' and ukcolumn = '" + listView1.Items[i].Text + "'";
}
}
To delete the rows safly, you can save the item name in a array and then remove them after you go through the whole list.
This assumes that you use unique names for each one, if the Name properie is not used at all you can add a Name specificly for the deletion.
List<string> toDelete = new List<int>;
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Checked == true)
{
toDelete.Add(listView1.Items[0].Name);
string sql = "uscolumn = '" + listView1.Items[i].Text + "' and ukcolumn = '" + listView1.Items[i].Text + "'";`
}
}
foreach(string name in toDelete)
listView1.ItemsRemoveByKey(name);
Another way to do it would be to remove 1 from i each time you delete.
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Checked == true)
{
string sql = "uscolumn = '" + listView1.Items[i].Text + "' and ukcolumn = '" + listView1.Items[i].Text + "'";
listView1.Items.RemoveAt(i--);
}
}

Categories

Resources