drop down comboBox if else statement error [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
If I write in cmbGrNo.text then there will be an
Input string is not in correct format
How can I identify that which combobox is edit?
I write in combobox and then click on search button the compiler is giving me error cause it does not accept the other combobox text. It only accepts the value of first one ...
please help me
HERE IS THE CODE
private void btnSearch_Click(object sender, EventArgs e)
{
if (cmbAdmissionNo.Text.Length == 0 && cmbRollNo.Text.Length == 0 && cmbStudentName.Text.Length == 0 && cmbGRNo.Text.Length == 0)
{
MessageBox.Show("Enter Student Name OR Admission No OR Gr No OR Roll No"," INSERT FIELDS", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if (StudentDBClass.CheckStudent(cmbStudentName.Text))
{
DataTable dt = StudentDBClass.getTableBYStdName(cmbStudentName.Text);
txtAdminNo.Text = "Admission No : " + dt.Rows[0]["AddmissionNo"];
txtGrNo.Text = "GR No : " + dt.Rows[0]["GRNo"];
txtClass.Text = "Class : " + dt.Rows[0]["ClassName"];
txtStudentName.Text = "Student Name : " + dt.Rows[0]["StudentName"];
txtFatherName.Text = "Father Name : " + dt.Rows[0]["FatherName"];
txtRollNo.Text = "Roll No: " + dt.Rows[0]["RollNo"];
dgvStdFeeCollection.DataSource = null;
dgvStdFeeCollection.DataSource = StudentFeeCollectionDBClass.getStdNameForDgvFeeCollection(cmbStudentName.Text);
cmbAdmissionNo.SelectedIndex = -1;
cmbGRNo.SelectedIndex = -1;
cmbRollNo.SelectedIndex = -1;
cmbAdmissionNo.Text = string.Empty;
cmbGRNo.Text = string.Empty;
cmbRollNo.Text = string.Empty;
}
else if (StudentDBClass.CheckWithAdmissionNo(Convert.ToInt32(cmbAdmissionNo.Text)))
{
DataTable dt = StudentDBClass.getTableBYAddmissionNo(Convert.ToInt32(cmbAdmissionNo.Text));
txtAdminNo.Text = "Admission No : " + dt.Rows[0]["AddmissionNo"];
txtGrNo.Text = "GR No : " + dt.Rows[0]["GRNo"];
txtClass.Text = "Class : " + dt.Rows[0]["ClassName"];
txtStudentName.Text = "Student Name : " + dt.Rows[0]["StudentName"];
txtFatherName.Text = "Father Name : " + dt.Rows[0]["FatherName"];
txtRollNo.Text = "Roll No: " + dt.Rows[0]["RollNo"];
dgvStdFeeCollection.DataSource = null;
dgvStdFeeCollection.DataSource = StudentFeeCollectionDBClass.getAdmissionNoForDgvFeeCollection(Convert.ToInt32(cmbAdmissionNo.Text));
cmbStudentName.SelectedIndex = -1;
cmbGRNo.SelectedIndex = -1;
cmbRollNo.SelectedIndex = -1;
cmbGRNo.Text = string.Empty;
cmbStudentName.Text = string.Empty;
cmbRollNo.Text = string.Empty;
}
else if (StudentDBClass.CheckGRNo(Convert.ToInt32(cmbGRNo.Text)))
{
DataTable dt = StudentDBClass.getTableGrNo(Convert.ToInt32(cmbGRNo.Text));
txtAdminNo.Text = "Admission No : " + dt.Rows[0]["AddmissionNo"];
txtGrNo.Text = "GR No : " + dt.Rows[0]["GRNo"];
txtClass.Text = "Class : " + dt.Rows[0]["ClassName"];
txtStudentName.Text = "Student Name : " + dt.Rows[0]["StudentName"];
txtFatherName.Text = "Father Name : " + dt.Rows[0]["FatherName"];
txtRollNo.Text = "Roll No: " + dt.Rows[0]["RollNo"];
dgvStdFeeCollection.DataSource = null;
dgvStdFeeCollection.DataSource = StudentFeeCollectionDBClass.getGrNoForDgvFeeCollection(Convert.ToInt32(cmbGRNo.Text));
cmbAdmissionNo.SelectedIndex = -1;
cmbStudentName.SelectedIndex = -1;
cmbRollNo.SelectedIndex = -1;
cmbAdmissionNo.Text = string.Empty;
cmbStudentName.Text = string.Empty;
cmbRollNo.Text = string.Empty;
}

This error occurs when the Convert.ToInt32 receives a string that its not able to parse.
You are selecting the text value of the combobox, this will not return an integer.
You need to select the SelectedValue of the combobox.
Something like this:
Convert.ToInt32(cmbGrNo.SelectedValue.Text)

Related

Keep int variables values from dataReader c#

I don't have much experience with C# but I am trying to make a simple windows forms app with personal finances.
So, I have 2 dataReader (I am using the Oracle provider), and the sql (oracle table) commands that select only 2 columns from a table, only with 1 value, mainly income 1 and income2 and the sum of all values from a specific month.
the sql strings look like this:
strSQL_sel_income1 = "select DISTINCT categorie,SUM(suma) from financiar where main_categ='income' and categorie IN ('income1') and EXTRACT(month FROM data)=" + luna_income + " Group by categorie";
strSQL_sel_income2 = "select DISTINCT categorie,SUM(suma) from financiar where main_categ='income' and categorie IN ('Income2') and EXTRACT(month FROM data)=" + luna_income + " Group by categorie";
the "luna_income" value is taken from a combobox where I select a specific month.
The problem is when I try to declare an Int variable from the values I get with data reader and these variables are not kept outside the while statement... dr_income1/2 being the dataReader
if (dr_income1.HasRows)
{
while (dr_income1.Read())
{
label26.Text = dr_income1.GetString(0) + ": " + dr_income1.GetInt32(1) + "\n";
int suma_income1 = dr_incomei1.GetInt32(1);
}
}
else
{
label26.Text = "No info;
}
so, I have two similar data readers and two int variables suma_income1 and suma_income2. If I try to make a sum of them, outside the WhIle codes, I get a zero value. Where should I declare the two variables and how to keep their values?
int suma_income_total = suma_income1 + suma_income2;
label29.Text = "Income total: " + suma_income_total;
The suma_income_total is ZERO!!!
dr_income1 = cm1.ExecuteReader();
dr_income2 = cm2.ExecuteReader();
label26.Text = "";
label28.Text = "";
if (dr_income1.HasRows)
{
while (dr_income1.Read())
{
label26.Text = dr_income1.GetString(0) + ": " + dr_income1.GetInt32(1) + "\n";
int suma_income1 = dr_income1.GetInt32(1);
}
}
else
{
label26.Text = "No info";
}
if (dr_income2.HasRows)
{
while (dr_income2.Read())
{
label28.Text = dr_income2.GetString(0) + ": " + dr_income2.GetInt32(1) + "\n";
int suma_income2 = dr_income2.GetInt32(1);
}
}
else
{
label28.Text = "no info";
}
int suma_income_total = suma_income1 + suma_income2;
label29.Text = "income total: " + suma_income_total;
dr_income2.Close();
dr_income1.Close();
I put some changes in your code. It is not ideal since there are several much simple ways. But it is ok as workaround:
dr_income1 = cm1.ExecuteReader();
dr_income2 = cm2.ExecuteReader();
label26.Text = "";
label28.Text = "";
var suma_income1 =0;
var suma_income2 =0;
if (dr_income1.HasRows)
{
while (dr_income1.Read())
{
label26.Text = dr_income1.GetString(0) + ": " + dr_income1.GetInt32(1) + "\n";
suma_income1 += dr_income1.GetInt32(1);
}
}
else
{
label26.Text = "No info";
}
if (dr_income2.HasRows)
{
while (dr_income2.Read())
{
label28.Text = dr_income2.GetString(0) + ": " + dr_income2.GetInt32(1) + "\n";
suma_income2 += dr_income2.GetInt32(1);
}
}
else
{
label28.Text = "no info";
}
int suma_income_total = suma_income1 + suma_income2;
label29.Text = "income total: " + suma_income_total;
dr_income2.Close();
dr_income1.Close();

Doesn't parse updated row from LinqToSQLDataClass to Database LINQ C# WPF

I'm building an Edit/Update system in my program using Linq in C# WPF.
My problem is that my code does submit to the LinqToSQLDatacontex but doesn't parse it through to the actual Database.
The result of that is that the datarow is updated in Runtime but in fact isn't updated in the actual Database.
this is the code I use for Updating my rows.
private void dgUsers_MouseUp(object sender, MouseButtonEventArgs e)
{
try
{
item = dgUsers.SelectedItem;
this.name = (dgUsers.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
var query =
from t in db.tbl_Users
where t.Name == name
select t;
foreach (var q in query)
{
tbMoreName.Text = q.Name;
tbMoreRights.Text = q.Rights;
tbMoreTag.Text = q.Operatortag;
checkMoreActive.IsChecked = q.Active;
tbMoreCardCode.Text = q.CardCode;
}
var table =
from q in db.tbl_UserProfiles
where q.Userprofile == tbMoreRights.Text
select q;
}
catch (Exception exc)
{
MessageBox.Show("NOPE");
}
}
private void btnSaveUser_Click(object sender, RoutedEventArgs e)
{
switch (saveType)
{
case "Edit":
#region save Edit User
var edit =
(from t in db.tbl_Users
where t.Name == name
select t).First();
MessageBox.Show(edit.Id.ToString() + " " + edit.Name.ToString() + " " + edit.Operatortag.ToString() + " " + edit.Rights.ToString() + " " + edit.Active.ToString());
edit.Id = edit.Id;
edit.Name = tbName.Text;
edit.Operatortag = tbOperatortag.Text;
edit.Rights = cbRights.Text;
edit.Active = checkActive.IsChecked.Value;
edit.CardCode = tbCardcode.Text;
MessageBox.Show(edit.Id.ToString() + " " + edit.Name.ToString() + " " + edit.Operatortag.ToString() + " " + edit.Rights.ToString() + " " + edit.Active.ToString() + " " + edit.CardCode.ToString());
db.SubmitChanges();
#endregion
saveType = "";
break;
}
var refresh =
(from q in db.tbl_Users
select new { Name = q.Name, Rights = q.Rights, Operatortag = q.Operatortag, Active = q.Active, Cardcode = q.CardCode }).ToList();
dgUsers.ItemsSource = null;
dgUsers.ItemsSource = refresh;
MessageBox.Show(refresh[0].ToString() + " " + refresh[1].ToString() + " " + refresh[2].ToString() + " " + refresh[3].ToString() + " " + refresh[4].ToString());
}
I hope that one of you guys can help me.
Thanks in advance!!!

Make a string bold that is displayed in both a RadGrid txtNote and a label

I have a RadGrid that shows a txtNote as text in its note column. I also have a label called lblShowAllSessionNotes. When A session note is added or appended to an existing note, a type of ID stamp preceeds the actual txt message, like so:
NoteTYPE - CommunicationType - ContactType
Electronically signed by: someone's Name 6/12/2016 12:00:00
This is the note text. It is text.
If I put ... in the string variable in code behind, then in the radGrid it appears as: Electronically signed by: someone's name; instead of Electronically signed by: someone's name.... In the label it appears bold as expected.
I have a method:
/// <summary>
/// Creates and shows all session notes in a text format.
/// </summary>
protected void ShowAllSessionNotes()
{
var allNotes = new StringBuilder();
string splitStr = "";
string[] newStr = null;
foreach (var noteItem in SessionNotes())
{
allNotes.Append("<b>" + noteItem.DmSessionNoteType + " - </b>");
allNotes.Append("<b>" + noteItem.DmCommunicationType + " - </b>");
allNotes.Append("<b>" + noteItem.DmContactType + " - </b>");
allNotes.Append(noteItem.AddDateTime + " (CST)");
if (ShowDuration)
{
allNotes.AppendFormat(" - <b>Duration:</b> {0} - <b>Electronically signed by: </b> {1}",
FormatDuration(noteItem.Duration), noteItem.CCName);
}
if (noteItem.Note.Contains('|'))
{
splitStr = noteItem.Note;
newStr = splitStr.Split('|');
noteItem.Note = String.Join("<br/>", newStr);
}
if (noteItem.Note.Contains(':') && noteItem.Note.StartsWith("Electronically"))
{
splitStr = noteItem.Note;
string bldStr = splitStr.Split(':')[0];
}
allNotes.Append("<br />");
allNotes.Append(noteItem.Note);
allNotes.Append("<br /><br />");
}
lblShowAllSessionNotes.Text = allNotes.ToString();
lblShowAllSessionNotes.Visible = true;
}
and another....
/// <summary>
/// Helper function that populates a session note entity.
/// </summary>
/// <param name="item">The GridEditableItem to pull data from.</param>
/// <param name="sessionNote">Existing PatientSessionNote entity.</param>
/// <returns>Returns a populated PatientSessionNote entity.</returns>
private PatientSessionNote PopulatePatientSessionNote(GridEditableItem item, ref List<string> errors)
{
var id = item.ItemIndex != -1 ? Convert.ToInt32(item.OwnerTableView.DataKeyValues[item.ItemIndex]["ID"]) : 0;
var rcb = item.FindControl("radCmbNoteType") as RadComboBox;
var rcbCC = item.FindControl("radCmbCommunicationType") as RadComboBox;
var rcbC = item.FindControl("radCmbContactType") as RadComboBox;
var rtb = item.FindControl("rtbNote") as RadTextBox;
string userSign = "Electronically signed by: ";
var appendDate = DateTime.Now;
var appendUser = User.Identity.Name;
var appendName = new MasterBLL().getUserName(appendUser);
var origSessNote = item.FindControl("HideOriginalSessionNote") as HiddenField;
string sessionNoteSent = "";
if (origSessNote.Value == "".Trim() || origSessNote == null)
{
sessionNoteSent = rtb.Text;
}
else
{
sessionNoteSent = origSessNote.Value + " | " + Environment.NewLine + userSign + appendName + " " + appendDate.ToString() + " | " + Environment.NewLine + rtb.Text;
}
var sessionNote = new PatientSessionNote
{
Id = id,
PatientId = _patientId,
DeleteReason = string.Empty,
IsDeleted = false,
LastUpdateDateTime = DateTime.Now,
LastUpdateUserName = CurrentUserId,
CommunicationTypeId = Convert.ToInt32(rcbCC.SelectedValue),
ContactTypeId = Convert.ToInt32(rcbC.SelectedValue),
SessionNoteTypeId = Convert.ToInt32(rcb.SelectedValue),
Note = Server.HtmlDecode(sessionNoteSent)
};
if (id == 0)
{
sessionNote.AddDateTime = DateTime.Now;
sessionNote.AddUserName = CurrentUserId;
}
if (ShowDuration)
{
var rdpSessionDate = item.FindControl("rdpSessionDate") as RadDatePicker;
var txtSessionStartTime = item.FindControl("txtSessionStartTime") as TextBox;
var txtSessionEndTime = item.FindControl("txtSessionEndTime") as TextBox;
//Set any existing values to NULL (for UPDATEs) so that validation doesn't allow incorrect inputs because of pre-existing old values
//This values will be redefined thru the standard INSERT practices
sessionNote.SessionStart = null;
sessionNote.SessionEnd = null;
sessionNote.Duration = 0;
if (rdpSessionDate != null && txtSessionStartTime != null && txtSessionEndTime != null)
{
var regexDate = Regex.Match(rdpSessionDate.DbSelectedDate.ToString(), #"\d{1,2}/\d{1,2}/\d{4}",
RegexOptions.Singleline);
if (regexDate.Success)
{
var startTime = Regex.Match(txtSessionStartTime.Text,
#"(?i)(?<Hours>\d{1,2}):(?<Minutes>\d{2})(?<Meridian>am|pm)", RegexOptions.Singleline);
var endTime = Regex.Match(txtSessionEndTime.Text,
#"(?i)(?<Hours>\d{1,2}):(?<Minutes>\d{2})(?<Meridian>am|pm)", RegexOptions.Singleline);
if (startTime.Success && endTime.Success)
{
//SessionStart & SessionEnd Dates
DateTime varDate;
if (DateTime.TryParse(rdpSessionDate.DbSelectedDate.ToString(), out varDate))
{
var startHours = int.Parse(startTime.Groups["Hours"].Value)%12;
var endHours = int.Parse(endTime.Groups["Hours"].Value)%12;
var startMinutes = int.Parse(startTime.Groups["Minutes"].Value);
var endMinutes = int.Parse(endTime.Groups["Minutes"].Value);
var isStartAM = Regex.IsMatch(startTime.Groups["Meridian"].Value.ToLower(), "am");
var isEndAM = Regex.IsMatch(endTime.Groups["Meridian"].Value.ToLower(), "am");
if (varDate != DateTime.MinValue)
{
var startDate = new DateTime(varDate.Year, varDate.Month, varDate.Day,
((isStartAM) ? startHours : (startHours + 12)), startMinutes, 0);
var endDate = new DateTime(varDate.Year, varDate.Month, varDate.Day,
((isEndAM) ? endHours : (endHours + 12)), endMinutes, 0);
var span = endDate.Subtract(startDate);
sessionNote.SessionStart = startDate;
if (span.TotalMinutes > 0)
//Only log if the amount of minutes is a positive number (integer)
{
sessionNote.SessionEnd = endDate;
sessionNote.Duration = (int) span.TotalMinutes;
}
else
{
errors.Add(#"The start time is greater than the end time");
errors.Add(#"Date chosen: " + rdpSessionDate.DbSelectedDate);
errors.Add(#"Start date time: " + startDate);
errors.Add(#"End date time: " + endDate);
errors.Add(#"Total minutes: " + span.TotalMinutes);
}
}
else
{
errors.Add(#"Invalid date format: " + rdpSessionDate.DbSelectedDate);
}
}
else
{
errors.Add(#"Invalid date format: " + rdpSessionDate.DbSelectedDate);
}
}
else
{
if (!startTime.Success)
{
errors.Add(#"Invalid start time format: " + txtSessionStartTime.Text);
}
if (!endTime.Success)
{
errors.Add(#"Invalid end time format: " + txtSessionEndTime.Text);
}
}
}
else
{
errors.Add(#"Invalid date format: " + rdpSessionDate.DbSelectedDate);
}
}
else
{
if (rdpSessionDate == null)
{
errors.Add(#"RadDatePicker ControlID ""rdpSessionDate"" could not be found");
}
if (txtSessionStartTime == null)
{
errors.Add(#"TextBox ControlID ""txtSessionStartTime"" could not be found");
}
if (txtSessionEndTime == null)
{
errors.Add(#"TextBox ControlID ""txtSessionEndTime"" could not be found");
}
}
}
if (errors.Count > 0)
{
errors.Add("Server date: " + DateTime.Today);
}
return sessionNote;
}
If I put the bold tag < b > in the second method PopulatePatientSessionNote(...) on string userSign then it works for the label but not for the grid. I appreciate the help!
Ok because of time constraints I've done this: It's messy but it works.
I first added a property:
public string UserSign { get; set; }
In The PopulatePatientSessionNote(...) method I added this:
UserSign = "" + userSign + "";
sessionNoteSent = origSessNote.Value + " | " + Environment.NewLine + "`" + appendName + " " + appendDate.ToString() + " | " + Environment.NewLine + rtb.Text;
Then in the ShowAllSessionNotes (...) method I added:
splitStr = noteItem.Note;
newStr = splitStr.Split('`');
noteItem.Note = String.Join(UserSign, newStr);
It's messy but it works. Does anyone one have a better idea? Thx a bunch!!!

even when details view insert fails the application is sending an email

I have an details view that is attached to a sql datasource. When a new workorder is inserted i am sending an email. Right now there is some issue with my program and the user is not able to insert the data from my application but the email still gets send assuming the data is inserted.
This is my Details View Inserted Method:
protected void DetailsView1_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
{
if (successfull == true && Page.IsValid && e.AffectedRows ==1)
{
//TextBox TextBoxWorkOrderNumber = (TextBox)(DetailsView1.FindControl("TextBox11"));
TextBox TextBoxRequestor = (TextBox)(DetailsView1.FindControl("TextBox3"));
TextBox TextBoxDate = (TextBox)(DetailsView1.FindControl("TextBox1"));
//TextBoxDate.Text = DateTime.Now.ToShortDateString();
TextBox TextBoxDepartment = (TextBox)(DetailsView1.FindControl("TextBox4"));
TextBox TextBoxCompletionDate = (TextBox)(DetailsView1.FindControl("TextBox16"));
TextBox TextBoxMachineDescription = (TextBox)(DetailsView1.FindControl("TextBox5"));
TextBox TextBoxMachineLocation = (TextBox)(DetailsView1.FindControl("TextBox6"));
TextBox TextBoxWorkRequired = (TextBox)(DetailsView1.FindControl("TextBox7"));
// DropDownList status = (DropDownList)(DetailsView1.FindControl("DropDownList2"));
TextBox TextBoxStatus = (TextBox)(DetailsView1.FindControl("TextBox12"));
TextBoxStatus.Text = "Open";
DropDownList list = (DropDownList)(DetailsView1.FindControl("DropDownList1"));
TextBox9.Text = list.SelectedValue;
DropDownList lists = (DropDownList)(DetailsView1.FindControl("DropDownList2"));
TextBox14.Text = lists.SelectedValue;
if (TextBoxRequestor.Text.Length <= 0)
{
TextBoxRequestor.Text = "Not Applicable";
}
if (TextBox14.Text.Length <= 0)
{
TextBoxDepartment.Text = "Not Provided";
}
if (TextBoxCompletionDate.Text.Length <= 0)
{
TextBoxCompletionDate.Text = "Not Provided";
}
if (TextBoxMachineDescription.Text.Length <= 0)
{
TextBoxMachineDescription.Text = "Not Provided";
}
if (TextBoxMachineLocation.Text.Length <= 0)
{
TextBoxMachineLocation.Text = "Not Provided";
}
if (TextBoxWorkRequired.Text.Length <= 0)
{
TextBoxWorkRequired.Text = "Not Provided";
}
if (TextBox9.Text == "Safety" && e.AffectedRows==1)
{
{
bool isLocal = HttpContext.Current.Request.IsLocal;
if (isLocal == true)
{
string id = TextBox13.Text.ToString();
System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage();
mm.From = new System.Net.Mail.MailAddress("no_reply_workorder#.com");//who send
mm.To.Add(new System.Net.Mail.MailAddress("abc#.com"));
//abc#abc.com
mm.Subject = "WorkOrders Type Safety";
mm.Body = "DO NOT REPLY TO THIS EMAIL" + "<br><br/>" + "WorkOrderNumber"
+ ": " + "<a href=\"http://localhost:49695/SafetyReport.aspx?WorkOrderNum=" + TextBox13.Text + "\">"
+ TextBox13.Text + "</a>" + "<-Click on the Work Order Number For Report"
+ "<br><br/>" + "WorkOrderNumber" + ": " +
"<a href=\"http://localhost:49695/Safety.aspx?WorkOrderNum=" +
TextBox13.Text + "\">" + TextBox13.Text + "</a>" +
"<-Click on this Work Order Number To Enter Data" +
"<br><br/>" + "Requestor" + ": " + TextBoxRequestor.Text +
"<br><br/>" + "Date" + ": " + TextBoxDate.Text +
"<br><br/>" + "Department" + ": " + TextBox14.Text +
"<br><br/>" + "Machine Description" + ": " +
TextBoxMachineDescription.Text + "<br><br/>" +
"Machine Location" + ": " +
TextBoxMachineLocation.Text + "<br><br/>" +
"Work Required" + ": " + TextBoxWorkRequired.Text + "<br><br/>"
mm.IsBodyHtml = true;
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
client.Host = ConfigurationManager.AppSettings["smtpServer"];
client.Send(mm);
captureuseremail();
}
}
}
}
i see an DetailsView1_Item Inserting how can i check if that is inserting into the sql database?? if the inserting is successful i like to set a boolean value to true and if true then perform the Details_View1 Inserted and send email else cancel the insert.
i am also using the insert button that comes with the details view. please ask me for additional code if your confused and i would more than happily provide it.
please help :(
Added Additional code:
INSERT INTO Master(Requestor, Date, Department, CompletionDate, MachineDescription,
MachineLocation, [Type of Work Order], [Work Required], Status)
VALUES (#Requestor, #Date, #Department, #CompletionDate,
#MachineDescription, #MachineLocation, #Type_of_Work_Order,
#Work_Required, #Status); SET #NewId = Scope_Identity()
i just have a bool successfull; which i set to true at the end of Item_Inserting method().
when user clicks submit on the details view which is nothing but the command button insert then the code hits the item_inserting takes all the value
Item_Inserting of the details view:
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
if (Page.IsValid)
{
//TextBox TextBoxWorkOrderNumber = (TextBox)(DetailsView1.FindControl("TextBox11"));
TextBox TextBoxRequestor = (TextBox)(DetailsView1.FindControl("TextBox3"));
TextBox TextBoxDate = (TextBox)(DetailsView1.FindControl("TextBox1"));
//TextBoxDate.Text = DateTime.Now.ToShortDateString();
TextBox TextBoxDepartment = (TextBox)(DetailsView1.FindControl("TextBox4"));
TextBox TextBoxCompletionDate = (TextBox)(DetailsView1.FindControl("TextBox16"));
TextBox TextBoxMachineDescription = (TextBox)(DetailsView1.FindControl("TextBox5"));
TextBox TextBoxMachineLocation = (TextBox)(DetailsView1.FindControl("TextBox6"));
TextBox TextBoxWorkRequired = (TextBox)(DetailsView1.FindControl("TextBox7"));
// DropDownList status = (DropDownList)(DetailsView1.FindControl("DropDownList2"));
TextBox TextBoxStatus = (TextBox)(DetailsView1.FindControl("TextBox12"));
TextBoxStatus.Text = "Open";
DropDownList list = (DropDownList)(DetailsView1.FindControl("DropDownList1"));
TextBox9.Text = list.SelectedValue;
DropDownList lists = (DropDownList)(DetailsView1.FindControl("DropDownList2"));
TextBox14.Text = lists.SelectedValue;
if (TextBoxRequestor.Text.Length <= 0)
{
TextBoxRequestor.Text = "Not Applicable";
}
if (TextBox14.Text.Length <= 0)
{
TextBoxDepartment.Text = "Not Provided";
}
if (TextBoxCompletionDate.Text.Length <= 0)
{
TextBoxCompletionDate.Text = "Not Provided";
}
if (TextBoxMachineDescription.Text.Length <= 0)
{
TextBoxMachineDescription.Text = "Not Provided";
}
if (TextBoxMachineLocation.Text.Length <= 0)
{
TextBoxMachineLocation.Text = "Not Provided";
}
if (TextBoxWorkRequired.Text.Length <= 0)
{
TextBoxWorkRequired.Text = "Not Provided";
}
successfull = true;
}
else
{
e.Cancel = true;
successfull = false;
}
}
This is Where the actual insert takes place, its my sqldatasource:
**all the values from the item_inserting are inserted here with an identity value **
protected void RequestorSource_Inserted(object sender, SqlDataSourceStatusEventArgs e)
{
if (successfull == true)
{
try
{
int newid = (int)e.Command.Parameters["#NewId"].Value;
TextBox13.Text = newid.ToString();
}
catch
{
successfull = false;
}
if (e.AffectedRows == 1 && successfull == true)
{
successfull = true;
}
else
{
successfull = false;
}
}
else
{
successfull = false;
}
}
the issue is the email is still getting sent when i stop the program, how can i create a bad insert like i want it to fail similar what is happening to the user i am not able to recreate the issue for example i tried adding a new field in the insert statement but did not give it any values and the error it threw was you have more columns then values.
This is a picture of my details view:
**all of the .cs code at http://pastebin.com/6VC6FZK7 and the .aspx code at http://pastebin.com/QhjWNNt0 ** hope this helps out a bit.
If you just setting the bool successful to true after the insert and have not done any error checking then it can fail and still send the email. I suggest either wrapping the insert code in a TRY..CATCH..and set the succssful state to false in the catch OR running a IF...ELSE.. to check if the data was inserted correctly and setting the successful state there.

Show Brackets in Asp.net

when users login to their account then i show their names and also their designations it works but when i show designation it shows like mix means that username+designation for example JOHNMANAGER .here manager is desgination and same like this happend in my side but i want designations type in brackets.
here is code
string desginname = Convert.ToString(loginusers.spdesignname(txt_username.Value, txt_pass.Value));
Session["UserDesignationName"] = desginname;
if (users == 1)
{
Session["Login2"] = txt_username.Value;
Session["Login3"] = txt_pass.Value;
Session["UserDesignationID"] = desginid;
//Session["DepartmentID"] = depid; ;
Session["UserDesignationName"] = desginname;
Session["UserTypeID"] = users;
Response.Redirect("alldocuments.aspx");
}
else if (users == 2)
{
Session["Login2"] = txt_username.Value;
Session["Login3"] = txt_pass.Value;
Session["UserDesignationID"] = desginid;
Session["UserDesignationName"] = desginname;
Session["UserTypeID"] = users;
Response.Redirect("alldocuments.aspx");
}
}
catch
{
errrros.Text = "Incorrect User Name or Password";
}
and here is in site master ...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["Login2"] != null & Session["UserDesignationName"]!=null)
{
["UserDesignationID"].ToString();
WELCOME.Text = Session["Login2"].ToString() +Session
[("UserDesignationName")].ToString();
}
lbtnLogout.Visible = Session["Login2"] != null || Session["Login2"] !=
null;
}
}
and here is the image
image
Add them in where you build the welcome text:
WELCOME.Text = Session["Login2"].ToString() + " (" + Session
[("UserDesignationName")].ToString() + ")";
or better, use String.Format:
WELCOME.Text = String.Format("{0} ({1})",
Session["Login2"].ToString(),
Session[("UserDesignationName")].ToString());
Try This.
WELCOME.Text = Session["Login2"].ToString() +
" (" + Session["UserDesignationName"].ToString() +")";
Just use following line of code if designation name is not supplied.
WELCOME.Text = Session["Login2"].ToString() + (Session["UserDesignationName"].ToString()!="" ? " (" + Session["UserDesignationName"].ToString() + ")" : string.Empty) ;

Categories