If ELSE condition not working properly - c#

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
}
}

Related

Inserting Multiple selected Listbox items into the same cell in SQL table

I want to insert multiple list box items into a a cell In SQL table with a comma dividing the items. The code posted below will only add the first selected item within a listbox. Hence If you select 2 or 10 items the first one u selected will be Inserted into the table. The for loop is my problem, I need to get all the selected values.
Thanks
protected void pg_upload_Click(object sender, EventArgs e)
{
using (SqlConnection mycon = new SqlConnection(connectionstring))
{
using (SqlCommand mycmd = mycon.CreateCommand())
{
if (textbox_make.Text == string.Empty || textbox_number.Text == string.Empty)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('The Make/Model and Number must be Entered')", true);
}
else
{
string str = "";
for (int i=0; i<= listbox_software.Items.Count; i++)
{
str = listbox_software.SelectedItem.ToString();
}
mycon.Open();
mycmd.CommandText = "INSERT INTO tbl_PG (Model, PGNumber, AssetNo, Area, Owner,IPAddress, SerialNo, OSVersion, Memory, Software) " +
"Values ('" + textbox_make.Text + "' , '" + textbox_number.Text + "' , '" + textbox_asset.Text + "' , '" + drop_area.Text + "' , '" + drop_owner.Text + "' , '" + textbox_ip.Text + "' " +
", '" + textbox_serial.Text + "' , '" + textbox_os.Text + "' , '" + textbox_memory.Text + "' , '" + str + "')";
mycmd.ExecuteNonQuery();
PopulateGridView();
lblsuscessmessage.Text = "Selected Record Added";
lblerrormessage.Text = "";
textbox_make.Text = string.Empty;
textbox_number.Text = string.Empty;
textbox_asset.Text = string.Empty;
textbox_ip.Text = string.Empty;
textbox_serial.Text = string.Empty;
textbox_os.Text = string.Empty;
textbox_memory.Text = string.Empty;
}
}
}
}
Add following namespace:
using System.Linq;
Create a string array of selected items and then use string.join:
var selection = listbox_software.SelectedItems
.Cast<string>()
.ToArray();
var str = string.Join(",", selection);
I found out the answer.
// To access checkbox list item's value //
string total = "";
foreach (ListItem listItem in listbox_software.Items)
{
if (listItem.Selected)
{
total = total + "[" + listItem.Value + "][ " + " ";
}
}
string str = total.ToString();

Get all items of listbox by converting it in string values

I have listbox and its items are the selected dates from Calendar control in ASP.net. Now I need to filter them in foreach loop according to whether every single date is present database table or not. And the code for same I used is like as:
foreach (string item in ListBoxSelectedDates.Items)
{
string q = "select count(*) from event_calendar where _date='" + Convert.ToDateTime(item).ToString("yyyy-MM-dd") + "'";
MySqlCommand cmd = new MySqlCommand(q, conn);
conn.Open();
if ((long)(cmd.ExecuteScalar() ?? 0) == 0)
{
strBody += i + ". " + Convert.ToDateTime(item).ToString("dd-MMM-yyyy") + ", " + Convert.ToDateTime(item).DayOfWeek + " : Leave <br>";
i++;
}
else
{
strBody += i + ". " + Convert.ToDateTime(item).ToString("dd-MMM-yyyy") + ", " + Convert.ToDateTime(item).DayOfWeek + " : Holiday <br>";
i++;
}
conn.Close();
}
And getting error at first line of above code is:
Unable to cast object of type 'System.Web.UI.WebControls.ListItem' to
type 'System.String'.
I am not getting proper solution after continuously trying...
foreach (var _iterator in ListBoxSelectedDates.Items) // here "lstDate" is name of your list where you store all date.
{
string item = _iterator.ToString();
string q = "select count(*) from event_calendar where _date='" + Convert.ToDateTime(item).ToString("yyyy-MM-dd") + "'";
MySqlCommand cmd = new MySqlCommand(q, conn);
conn.Open();
if ((long)(cmd.ExecuteScalar() ?? 0) == 0)
{
strBody += i + ". " + Convert.ToDateTime(item).ToString("dd-MMM-yyyy") + ", " + Convert.ToDateTime(item).DayOfWeek + " : Leave <br>";
i++;
}
else
{
strBody += i + ". " + Convert.ToDateTime(item).ToString("dd-MMM-yyyy") + ", " + Convert.ToDateTime(item).DayOfWeek + " : Holiday <br>";
i++;
}
conn.Close();
}
You can use the ListItem.ToString() Method to convert the ListItem to a String.
foreach (var _iterator in ListBoxSelectedDates.Items)
{
string item = _iterator.ToString();
//The rest of your logic here
conn.Close();
}
If you want to access explicitly the value, you can have a look to the ListItem documentation, there you can see that there is a public property called Value so you can use instead:
string item = _iterator.Value;
so you get:
foreach (ListItem _iterator in ListBoxSelectedDates.Items)
{
string item = _iterator.Value;
//The rest of your logic here
conn.Close();
}

How to get controls from panel in asp.net 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
}
}

Dropdown list not appearing in Form

I'm adding a series of dropdown lists populated from a database to a page from code behind. Because I need a variable number of sections with each containing a variable number of dropdown lists, I'm having to run my queries and then put build and place the HTML straight onto the page. I'm sure there's a better way to do this (nested repeaters, possibly) but it is working. My HTML is:
Question
<input type='hidden' id='h100' />
<select id='q100'>
<option>Answer 1</option>
<option>Answer 2</option>
<option>Answer 3</option>
</select>
However, when the page POSTs back, I'm not getting these fields in the form collection. It's really odd because they seemed to be there yesterday, but then I come back to the page and can't find them.
Why would these not be appearing in the form collection after POST?
I'm using C# for code behind, any help is very appreciated.
Edit: Here is my code behind (please don't hurt me, I'm learning ASP.NET as I go):
if (!Page.IsPostBack)
{
// Much stuff that works fine, connecting to database, etc.
// Get matching questions - variables
ArrayList matchingSections = new ArrayList();
int matchingSectionCount;
// Get count of matching sections
OracleCommand cmdMatchSectCount = new OracleCommand("Select Count(distinct matching_section) From graphite.question Join graphite.q_matching Using(q_id) Where t_id = " + Session["TestTaking"].ToString(), conn);
OracleDataReader drMatchSectCount = cmdMatchSectCount.ExecuteReader();
drMatchSectCount.Read();
matchingSectionCount = (int)drMatchSectCount.GetOracleNumber(0).Value;
Session["MatchingSectionCount"] = matchingSectionCount;
// Get matching sections
OracleCommand cmdMatchSects = new OracleCommand("Select Distinct matching_section From graphite.question Join graphite.q_matching Using(q_id) Where t_id = " + Session["TestTaking"].ToString() + " Order By matching_Section", conn);
OracleDataReader drMatchSects = cmdMatchSects.ExecuteReader();
for(int i = 0; i < matchingSectionCount; i++)
{
drMatchSects.Read();
matchingSections.Add(drMatchSects.GetOracleString(0).Value);
}
foreach (String s in matchingSections)
{
string row = string.Empty;
int questionCount;
ArrayList answers = new ArrayList();
matchManual.InnerHtml += "\n<h2>Matching Section - " + s + "</h2>";
matchManual.InnerHtml += "\n<table>";
OracleCommand cmdQuestionCount = new OracleCommand("Select Count(correct_answer) From graphite.question Join graphite.q_matching Using(q_id) Where t_id = " + Session["TestTaking"].ToString() + " and matching_section = '" + s + "'", conn);
OracleDataReader drQuestionCount = cmdQuestionCount.ExecuteReader();
drQuestionCount.Read();
questionCount = int.Parse(drQuestionCount.GetOracleNumber(0).Value.ToString());
OracleCommand cmdMatchAnswers = new OracleCommand("Select correct_answer From graphite.question Join graphite.q_matching Using(q_id) Where t_id = " + Session["TestTaking"].ToString() + " and matching_section = '" + s + "' Order By correct_answer", conn);
OracleDataReader drMatchAnswers = cmdMatchAnswers.ExecuteReader();
for (int i = 0; i < questionCount; i++)
{
drMatchAnswers.Read();
answers.Add(drMatchAnswers.GetOracleString(0).Value.ToString());
}
OracleCommand cmdMatchLoop = new OracleCommand("Select q_phrase, q_id From graphite.question Join graphite.q_matching Using(q_id) Where t_id = " + Session["TestTaking"].ToString() + " and matching_section = '" + s + "'", conn);
OracleDataReader drMatchLoop = cmdMatchLoop.ExecuteReader();
for (int i = 0; i < questionCount; i++)
{
drMatchLoop.Read();
row += "\n <tr>";
row += "\n <td>" + drMatchLoop.GetOracleString(0).Value ;
row += "<input type='hidden' id='h" + drMatchLoop.GetOracleNumber(1).Value.ToString() + "' />";
row += "\n </td>";
row += "\n <td>";
row += "\n <select id='q" + drMatchLoop.GetOracleNumber(1).Value.ToString() + "' runat='server'>";
foreach(string answer in answers)
{
row += "\n <option>" + answer + "</option>";
}
row += "\n </select>";
row += "\n </td>";
row += "\n </tr>";
}
matchManual.InnerHtml += row;
matchManual.InnerHtml += "\n</table>\n\n";
}
Wow. Just...wow. With <select>, you have to include a name='value', not id='value'. Moral: know your HTML. And try harder to find ways to avoid spewing raw HTML onto a page.
If they are not present in the formcollection when submiting, I think the problem is they are not within a form tag that is submited, or you have to create the form tag and place the select tag in it.
#edited
Aha - so it was within a form, see now that the reason was the missing name attribute in the select tag!
The form collection uses the attribute name values as keys when posted.
I think that your Page.IsPostBack condition is source of problems. Because you are generating elements only on !IsPostback => only 'first' time, not after the post => they are missing after the post.

Update Statement Updates 0 Rows via the C# Winform Application?

First of all, please help me out! I can not take this anymore. I could not find where the error is located. Here is my problem:
I'm trying to update a row via c# winform application. The update query generated from the application is formatted correctly. I tested it in the sql server environment, it worked well. When i run it from the application i get 0 rows updated.
Here is the snippet that generates the update statement using reflection - don't try to figure it out. Carry on reading after the code portion:
public void Update(int cusID)
{
SqlCommand objSqlCommand = new SqlCommand();
Customer cust = new Customer();
string SQL = null;
try
{
if ((cusID != 0))
{
foreach (PropertyInfo PropertyItem in this.GetType().GetProperties())
{
if (!(PropertyItem.Name.ToString() == cust.PKName))
{
if (PropertyItem.Name.ToString() != "TableName")
{
if (SQL == null)
{
SQL = PropertyItem.Name.ToString() + " = #" + PropertyItem.Name.ToString();
}
else
{
SQL = SQL + ", " + PropertyItem.Name.ToString() + " = #" + PropertyItem.Name.ToString();
}
}
else
{
break;
}
}
}
objSqlCommand.CommandText = "UPDATE " + this.TableName + " SET " + SQL + " WHERE " + cust.PKName + " = #cusID AND PhoneNumber = " + "'" + "#phNum" + "'";
foreach (PropertyInfo PropertyItem in this.GetType().GetProperties())
{
if (!(PropertyItem.Name.ToString() == cust.PKName))
{
if (PropertyItem.Name.ToString() != "TableName")
{
objSqlCommand.Parameters.AddWithValue("#" + PropertyItem.Name.ToString(), PropertyItem.GetValue(this, null));
}
else
{
break;
}
}
}
objSqlCommand.Parameters.AddWithValue("#cusID", cusID);
objSqlCommand.Parameters.AddWithValue("#phNum", this.PhoneNumber);
DAL.ExecuteSQL(objSqlCommand);
}
else
{
//AppEventLog.AddWarning("Primary Key is not provided for Update.")
}
}
catch (Exception ex)
{
//AppEventLog.AddError(ex.Message.ToString)
}
}
This part below:
objSqlCommand.CommandText = "UPDATE " + this.TableName + " SET " + SQL + " WHERE " + cust.PKName + " = #cusID AND PhoneNumber = " + "'" + "#phNum" + "'";
generates dml:
UPDATE CustomerPhone SET PhoneTypeID = #PhoneTypeID, PhoneNumber = #PhoneNumber WHERE CustomerID = #cusID AND PhoneNumber = '#phNum'
#PhoneTypeID and #PhoneNumber are gotten from two properties. We assigned the value to these properties in the presentation layer from the user input text box. The portion below where fetches the values:
objSqlCommand.Parameters.AddWithValue("#" + PropertyItem.Name.ToString(), PropertyItem.GetValue(this, null));
The code below fills the values of WHERE:
objSqlCommand.Parameters.AddWithValue("#cusID", cusID);
objSqlCommand.Parameters.AddWithValue("#phNum", this.PhoneNumber);
The final code should look as:
UPDATE CustomerPhone
SET PhoneTypeID = 7, PhoneNumber = 999444
WHERE CustomerID = 500 AND PhoneNumber = '911';
Phone type id is 7 - user value that is taken from text box
Phone number is 999444 - user value that is taken from text box
The above final update statement works on the sql environment, but when running
via the application, the execute non query runs ok and gets 0 rows updated! I wonder why?
This is the problem:
AND PhoneNumber = '#phNum'
That's looking for a phone number which is exactly the text '#phNum' - it's not using a parameter called phNum. You want
AND PhoneNumber = #phNum
You're also breaking up your string literals for no obvious reason. This statement:
objSqlCommand.CommandText = "UPDATE " + this.TableName + " SET " + SQL +
" WHERE " + cust.PKName + " = #cusID AND PhoneNumber = " +
"'" + "#phNum" + "'";
would be more easily readable as:
objSqlCommand.CommandText = "UPDATE " + this.TableName + " SET " + SQL +
" WHERE " cust.PKName + " = #cusID AND PhoneNumber = '#phNum'";
Obviously you want to drop the single quotes from it, to make it just:
objSqlCommand.CommandText = "UPDATE " + this.TableName + " SET " + SQL +
" WHERE " cust.PKName + " = #cusID AND PhoneNumber = #phNum";
A little refactoring wouldn't go amiss, either. This loop:
foreach (PropertyInfo PropertyItem in this.GetType().GetProperties())
{
if (!(PropertyItem.Name.ToString() == cust.PKName))
{
if (PropertyItem.Name.ToString() != "TableName")
{
if (SQL == null)
{
SQL = PropertyItem.Name.ToString() + " = #" + PropertyItem.Name.ToString();
}
else
{
SQL = SQL + ", " + PropertyItem.Name.ToString() + " = #" + PropertyItem.Name.ToString();
}
}
else
{
break;
}
}
}
would be more simpler and more readable like this:
StringBuilder sqlBuilder = new StringBuilder();
foreach (PropertyInfo property in this.GetType().GetProperties())
{
string name = property.Name;
// I believe you had a bug before - the properties being updated
// would depend on the ordering of the properties - if it
// ran into "TableName" first, it would exit early!
// I *suspect* this is what you want
if (name != cust.PKName && name != "TableName")
{
sqlBuilder.AppendFormat("{0} = #{0}, ", name);
}
}
// Remove the trailing ", "
if (sqlBuilder.Length > 0)
{
sqlBuilder.Length -= 2;
}
You can do something similar with the final loop too.
Is PhoneNumber a string, or an integer?
I see you're SETting as a integer, but checking in the WHERE as a literal. Could this not be the problem?
If it's an integer, try:
UPDATE CustomerPhone
SET PhoneTypeID = 7, PhoneNumber = 999444
WHERE CustomerID = 500 AND PhoneNumber = 911;
If it's a string, try:
UPDATE CustomerPhone
SET PhoneTypeID = 7, PhoneNumber = '999444'
WHERE CustomerID = 500 AND PhoneNumber = '911';

Categories

Resources