I am encountering a problem when I attempt to enter information into a database that is connected to my visual studio 2012 form. When I start debugging if I enter information into the fields and hit submit, nothing gets entered into my database. If I enter the information again and hit submit, the information then will write to my database. I am not really great at programming, so I used the data sources to link my visual studio form and my database.
This is what my form looks like;
data form before entry
This is what my form looks like with data I enter;
data form with information
This is what happens when you hit submit;
confirmation message
This is the database after hitting submit the first time; db entries after first submission
This is what happens when I enter the information again; db entries after second submission
Any entries after this will enter correctly, and things are great. I am confused as to why information (besides the null entry) wont enter until the second time I click submit. While it "technically works" it's not quite right. Any help on the issue would be much appreciated.
Here is my code for my submit button in my New Customer Form;
namespace WindowsFormsApplication2
{
public partial class frmNewCustomer : Form
{
public frmNewCustomer()
{
InitializeComponent();
}
private void btnAddCustomer_Click(object sender, EventArgs e)
{
string cstFName;
string cstLName;
string cstAddress;
string cstCity;
string cstState;
string cstZip;
string cstPhone;
string cstEmail;
cstFName = cstFNameTxtBox.Text;
cstLName = cstLNameTxtBox.Text;
cstAddress = cstAddressTxtBox.Text;
cstCity = cstCityTxtBox.Text;
cstState = cstStateTxtBox.Text;
cstZip = cstZipTxtBox.Text;
cstPhone = cstPhoneTxtBox.Text;
cstEmail = cstEmailTxtBox.Text;
// exception handler for empty fields
if (cstFName == "")
{
MessageBox.Show("Please enter your first name!");
}
else if (cstLName == "")
{
MessageBox.Show("Please enter your last name!");
}
else if (cstAddress == "")
{
MessageBox.Show("Please enter your address!");
}
else if (cstCity == "")
{
MessageBox.Show("Please enter your city!");
}
else if (cstState == "")
{
MessageBox.Show("Please enter your state!");
}
else if (cstZip == "")
{
MessageBox.Show("Please enter your zip!");
}
else if (cstPhone == "")
{
MessageBox.Show("Please enter your Phone!");
}
else if (cstEmail == "")
{
MessageBox.Show("Please enter your email!");
}
else
{
MessageBox.Show("First Name: " + cstFName + " Last Name: " + cstLName + "\r\n" +
"Address: " + cstAddress + "\r\n" +
"City: " + cstCity + " State: " + cstState + " Zip: " + cstZip + "\r\n" +
"Phone: " + cstPhone + " Email: " + cstEmail + "\r\n" + "\r\n" +
"Has been added to the database.");
}
this.tblCustomersBindingSource.AddNew();
this.tblCustomersBindingSource.EndEdit();
this.tblCustomersTableAdapter.Update(this.dataSet1.tblCustomers); // Updating the DB Table
}
private void frmNewCustomer_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dataSet1.tblCustomers' table. You can move, or remove it, as needed. Loads it into start of form!
// this.tblCustomersTableAdapter.Fill(this.dataSet1.tblCustomers);
}
}
}
I realize my exception handling is janky at best, but this is more about creating a few forms that read and write data to a db. I appreciate any help anyone is able to offer,
If this weren't winforms (not sure that it matters), the typical flow is this:
Create a connection.
Write your insert statement.
Do data validation.
Submit to database.
Commit transaction.
try this:
bool shouldSubmit = false;
// exception handler for empty fields
if (cstFName == "")
{
MessageBox.Show("Please enter your first name!");
}
else if (cstLName == "")
{
MessageBox.Show("Please enter your last name!");
}
else if (cstAddress == "")
{
MessageBox.Show("Please enter your address!");
}
else if (cstCity == "")
{
MessageBox.Show("Please enter your city!");
}
else if (cstState == "")
{
MessageBox.Show("Please enter your state!");
}
else if (cstZip == "")
{
MessageBox.Show("Please enter your zip!");
}
else if (cstPhone == "")
{
MessageBox.Show("Please enter your Phone!");
}
else if (cstEmail == "")
{
MessageBox.Show("Please enter your email!");
}
else
{
shouldSubmit = true;
MessageBox.Show("First Name: " + cstFName + " Last Name: " + cstLName + "\r\n" +
"Address: " + cstAddress + "\r\n" +
"City: " + cstCity + " State: " + cstState + " Zip: " + cstZip + "\r\n" +
"Phone: " + cstPhone + " Email: " + cstEmail + "\r\n" + "\r\n" +
"Has been added to the database.");
}
if(shouldSubmit)
{
this.tblCustomersBindingSource.AddNew();
this.tblCustomersBindingSource.EndEdit();
this.tblCustomersTableAdapter.Update(this.dataSet1.tblCustomers); // Updating the DB Table
}
Related
So Basically I'm working on this Desktop application using c# server and client and for some reason whenever I send a msg in chat it doesn't work for all users but when I send a private msg it's working and I'm not sure why.
my server code:
if (e.MessageString.Contains("#"))
{
if (e.MessageString.Substring(0, 3).Equals("All"))
{
if (!e.MessageString.Substring(4, 4).Equals("File"))
{
string toAll = e.MessageString.Substring(4, e.MessageString.Length - 4) + "\n";
server.Broadcast(toAll);
txtStatus.Dispatcher.Invoke((Action)delegate ()
{
txtStatus.Text += toAll;
});
}
else
{
System.Windows.MessageBox.Show("Cannot send a file to everyone!");
}
}
and this is my chat code:
private void btnSend_Click(object sender, RoutedEventArgs e)
{
System.Console.WriteLine("Send was clicked");
if (btnConnect.IsEnabled)
{
System.Windows.MessageBox.Show("Please connect to the local server!");
}
else if (listbox.SelectedIndex != -1)
{
if (txtMessage.Text.Length > 0 && !ifFileSelected && !txtMessage.Text.Equals(" ") && !txtMessage.Text.Equals("\n"))
{
client.WriteLine(listbox.SelectedItem.ToString().ToLower() + "#" + username + ": " + txtMessage.Text);
}
else if (ifFileSelected)
{
byte[] b1 = File.ReadAllBytes(op.FileName);
client.Write(listbox.SelectedItem.ToString() + "#File#" + fi.Name + "#");
client.Write(b1);
ifFileSelected = false;
}
else
{
System.Windows.MessageBox.Show("Please type something or choose a file to send!");
}
}
else
{
System.Windows.MessageBox.Show("Please select someone to send the message to!");
}
txtMessage.Text = "";
}
I am able to upload other file types to share point using the lines of code below. However, when I try to upload an uadio file I get an error that reads "The given path's format is not supported" on the line where it trys to create the directory and save the file on SharePoint. The line reads System.IO.Directory.CreateDirectory(pathString);
I am suspecting the backslashes in path below my be a problem
Path
public static string CMSdocs1drive = "\\\\myserver.sharepoint.com#SSL\\DavWWWRoot\\personal\\myname_myorganisation_org_com\\";
Code To Upload And Save To SharePoint
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload_Section55_6.HasFile)
{
if (ddlDocument.SelectedIndex == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + "Upload status: Please select the document type." + "');", true);
}
else
{
try
{
if (FileUpload_Section55_6.PostedFile.ContentLength < 2014572800)
{
{
if (ddlFilingType.SelectedIndex != 0)
{
if (!String.IsNullOrEmpty(lblCaseID0.Text) && ddlDocument.SelectedValue.ToString() == "203")
pathString = CMSProperties.CMSdocs1drive + "\\" + lblCaseID0.Text + "\\" + ddlFilingType.SelectedItem.Text + "\\" + ".Mp3";
}
if (!Directory.Exists(pathString))
{
System.IO.Directory.CreateDirectory(pathString);
// System.IO.Directory.Move(pathString);
}
if (pathString != controller.CheckIfFilePathExist(pathString))
{
controller.UploadFile(pathString, lblCaseID.Text);
}
}
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + "Upload status: The file is to big!" + "');", true);
}
ddlDocument.SelectedIndex = 0;
}
catch (Exception ex)
{
ex.Message.ToString();
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + "Upload status: The file could not be uploaded. The following error occured:" + "');" + ex, true);
Console.WriteLine();
}
}
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + "Upload status: Please select file " + "');", true);
}
}
I am suspecting the backslashes in path below my be a problem
Consider using a Verbatim Operator( # ) for the path to denote that it contains escape sequence characters (the \ symbol) that should be ignored.
public static string CMSdocs1drive = "\\\\myserver.sharepoint.com#SSL\\DavWWWRoot\\personal\\myname_myorganisation_org_com\\";
with the verbatim operator you can avoid the use of additional escape sequence characters, for example:
public static string CMSdocs1drive = #"\\myserver.sharepoint.com#SSL\DavWWWRoot\personal\myname_myorganisation_org_com\";
I'm trying to make a button that takes the coordinates from the current location, calls the city from API and returns the name of the city in the searchbar.
At the moment when the button is pressed, it first asks for GPS permission but once you enable it it stops executing the logic down.
After permission, you need to press the same button again to change the name of the city in the search engine. Is there a way when the user allows the use of his location to execute the code without having to press a second time.
Code:
async void OnGetGPSLocation(System.Object sender, System.EventArgs e)
{
var status = await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>();
if (status == PermissionStatus.Denied && status == PermissionStatus.Disabled)
{
_ = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
}
else
{
try
{
var location = await Geolocation.GetLastKnownLocationAsync();
if (location != null)
{
WeatherForecast16DaysCoordinates weatherBindingData = await _restServiceForecastCoords.GetCity(GenerateRequestUriForecast3(ConstantsForecast16DaysCoords.WeatherbitEndPoint3, location));
var cityCoord = weatherBindingData.CityName;
_cityEntry.Text = cityCoord;
}
}
catch (FeatureNotSupportedException fnsEx)
{
await DisplayAlert("Alert" + Environment.NewLine + "Something is wrong.", "You have some errors: " + Environment.NewLine + fnsEx.ToString(), "OK");
}
catch (FeatureNotEnabledException fneEx)
{
await DisplayAlert("Alert" + Environment.NewLine + "Something is wrong.", "You have some errors: " + Environment.NewLine + fneEx.ToString(), "OK");
}
catch (PermissionException pEx)
{
await DisplayAlert("Alert" + Environment.NewLine + "Something is wrong.", "You have some errors: " + Environment.NewLine + pEx.ToString(), "OK");
}
catch (Exception ex)
{
await DisplayAlert("Alert" + Environment.NewLine + "Something is wrong.", "You have some errors: " + Environment.NewLine + ex.ToString(), "OK");
}
}
}
My second problem with GPS is when GPS is disconnected from the user's device. How to forward it directly to the settings to activate it.
when GPS is disconnected from the user's device. How to forward it directly to the settings to activate it.
If you want to allow the permission again when user deny it you could check the following code.
var bundleId = NSBundle.MainBundle.BundleIdentifier;
var url = new NSUrl(UIApplication.OpenSettingsUrlString + "&path=LOCATION/" + bundleId);
if(UIApplication.SharedApplication.CanOpenUrl(url))
{
UIApplication.SharedApplication.OpenUrl(url);
}
if (username.Text == "" && password.Text == "")
{
MessageBox.Show("Please Enter Username and Password");
}
if (!File.Exists(username.Text + ".txt"))
{
err.SetError(username, "Username not exist"); //sets the error
//MessageBox.Show("Please Enter Your Username");
}
else
{
err.SetError(username, ""); //clears the error
err.SetError(password, "");
TextReader tr = new StreamReader(username.Text + ".txt");
string pass = tr.ReadLine();
if (pass == password.Text)
{
app.Show();
this.Hide();
}
else
{
err.SetError(password, "Password Incorrect");
// MessageBox.Show("Please Enter Your Password");
}
The issue I have occured when I tested the login with empty username and empty password, both error warning of username and message box that says "please enter username and password" show. How do I solve this so that when enter nothing will show the message box? And when user enter incorrect username or password, the warning will show for either?
I'm currently using C# Windows Forms.
The problem is your code continues after your first if statement.
You could either put a return in the if statement:
if (username.Text == "" && password.Text == "")
{
MessageBox.Show("Please Enter Username and Password");
return;
}
Or you could change the second if to an else if:
if (username.Text == "" && password.Text == "")
{
MessageBox.Show("Please Enter Username and Password");
}
else if (!File.Exists(username.Text + ".txt"))
{
err.SetError(username, "Username not exist"); //sets the error
//MessageBox.Show("Please Enter Your Username");
} else {
....
}
This way the !File.Exists doesn't get executed if the username and password are empty.
Put return
Try this :
if (username.Text == "" && password.Text == "")
{
MessageBox.Show("Please Enter Username and Password");
return;
}
if (!File.Exists(username.Text + ".txt"))
{
err.SetError(username, "Username not exist"); //sets the error
//MessageBox.Show("Please Enter Your Username");
}
else
{
err.SetError(username, ""); //clears the error
err.SetError(password, "");
TextReader tr = new StreamReader(username.Text + ".txt");
string pass = tr.ReadLine();
if (pass == password.Text)
{
app.Show();
this.Hide();
}
else
{
err.SetError(password, "Password Incorrect");
// MessageBox.Show("Please Enter Your Password");
}
I have a sensor that connected to pc and data comes continuously like this picture:
I want to add two start and stop button and save data from start button pressed time and stop saving data when pressed stop button.
I write this code:
richTextBox1.AppendText(textBox1.Text + "\n");
System.IO.File.WriteAllLines(#"C:\Users\Mohammad_Taghi\Desktop\a.txt",richTextBox1.Lines);
but this code save whole of data in .txt file and is not controllable.
this is that part of code on richtextbox2:
public void detectFingers(Leap.Frame frame)
{
foreach(Finger finger in frame.Fingers)
{
richTextBox2.AppendText("Finger ID: " + finger.Id + Environment.NewLine +
"Finger Type: " + finger.Type + Environment.NewLine +
"Finger Length:" + finger.Length + Environment.NewLine +
"Finger width:" + finger.Width + Environment.NewLine);
foreach (Bone.BoneType boneType in (Bone.BoneType[])Enum.GetValues(typeof(Bone.BoneType)))
{
Bone bone = finger.Bone(boneType);
richTextBox3.AppendText("Bone Type: " + bone.Type +Environment.NewLine +
"Bone Length: " +bone.Length +Environment.NewLine+
"Bone Width : " + bone.Width +Environment.NewLine +
"Previous Joint : "+bone.PrevJoint + Environment.NewLine+
"Next Joint :" + bone.NextJoint + Environment.NewLine+
"Direction : " + bone.Direction + Environment.NewLine+;
}
}
}
As data comes in continuously you need to save from when the data should be stored uptil when. Printing the textBox1.Text will, of course, print everything.
You need to set a variable to store the information after the "Start" button is pressed until the "Stop" button is pressed. Here is some code:
private bool isLogging = false;
private string myLog = "";
//This is where the input from the sensor arrives
private void myInput(string s)
{
textBox1.Text += s + "\n";
if (isLogging)
myLog += s + "\n";
}
private void buttonOnStart_Click(object sender, EventArgs e)
{
//Clear log string
myLog = "";
//Start logging
isLogging = true;
}
private void buttonOnStop_Click(object sender, EventArgs e)
{
//Stop logging
isLogging = false;
//Pring only the logged messages
System.IO.File.WriteAllLines(#"C:\Users\Mohammad_Taghi\Desktop\a.txt", myLog);
}