I've written this code to change the serialport name:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
serialPort1.PortName = (string)comboBox1.SelectedValue;
}
catch (Exception)
{
MessageBox.Show("The SerialPorts's Name Does Not Change !! ");
}
}
The result is that I get an Exception. The SerialPort's name never changes.
Could be one of many issues.
Is (string)comboBox1.SelectedValue String.Empty?
Is (string)comboBox1.SelectedValue null?
Is serialPort1 open?
It would be easier to answer the question if we had the actual exception message, instead of the custom message you defined.
To use the SelectedValue Mr. JaredPar MSFT explained ComboBox SelectedItem, SelectedValue, SelectedWhat???.
I guess, your trying get the PortName not the SelectedValue
Solution:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == -1) return;
if (string.IsNullOrWhiteSpace(comboBox1.Text)) return;
serialPort1.PortName = comboBox1.Text;
}
or
your trying get the SelectedValue not the PortName
Solution:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue == null) return;
if (string.IsNullOrWhiteSpace(comboBox1.Text)) return;
serialPort1.PortName = (int)comboBox1.SelectedValue ;
}
Try to check your properties of ComboBox
Where: Display Member is your PortName
Value Member is your PortId or SelectedValue
You have to put a check in to see if the SelectedIndex is -1 or SelectedValue (or SelectedItem) is null. That's the value when there is no selected item.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == -1)
return;
serialPort1.PortName = (string)comboBox1.SelectedValue;
}
In order to figure out what the exception message is, try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
serialPort1.PortName = (string)comboBox1.SelectedValue;
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
The problem is that you don't handle exception properly. The exception that is thrown probably tells you what is the problem, but you're not looking at it.
Change your catch statement to
catch (Exception e) { MessageBox.Show(e.Message); }
Then see what is the exception, and fix it accordingly.
The SerialPort.PortName setter can throw an array of exceptions, so you need to know which one is it.
Related
I am trying to make a simple product code search using a datagridview.
I am able to filter the database but not able to get all the functions I want
I currently have it set as
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
productsBindingSource.Filter = string.Format("Type = '{0}'",
comboBox1.SelectedItem.ToString());
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
productsBindingSource.Filter = string.Format("Type = '{0}' AND Fitting = '{1}'",
comboBox1.SelectedItem.ToString(),
comboBox2.SelectedItem.ToString());
}
This code works but after the selections are made and I change comboBox1 the data resets and doesn't keep the selection of comboBox2.
I understand in my current code that this would not happen but I cannot figure out how to get this to happen.
I would also like to add a text box in the future and have it narrow the filter even more.
You should approach this a bit more generically like so
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
FilterProducts();
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
FilterProducts();
}
// Create a function to handle filters
private void FilterProducts()
{
string filter = "";
if (comboBox1.SelectedItem != null)
{
filter += string.Format("Type = '{0}'", comboBox1.SelectedItem.ToString());
}
if (comboBox2.SelectedItem != null)
{
if (filter.length > 0) filter += "AND "
filter += string.Format("Fitting = '{0}'", comboBox2.SelectedItem.ToString());
}
// Add another like above for your future textbox
// if (!string.IsNullOrEmpty(textBox1.Text))
// {
// if (filter.length > 0) filter += "AND "
// filter += string.Format("OtherColumn = '{0}'", textBox1.Text);
// }
productsBindingSource.Filter = filter;
}
The code could be further refactored for even better DRY standards but this should at least get you started.
I am trying to hide default datagridview error dialog.
I put in the code this event handler:
this.dataGridView2.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(dataGridView2_DataError);
private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
//empty so it doesn't show anything
}
But still when i try this and leave datagridview cell empty ( delete everything from it), it show me dialog box with error.
Screenshot of error:
Try to Handle and Cancel the event:
private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = true;
}
Also, subscribe to the event in InitializeComponent()
private void InitializeComponent()
{
//...
this.dataGridView.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dataGridView2_DataError);
}
try to use this code to handle the event:
private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = true;
}
Try the next code , it's work!
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
try
{
//To handle 'ConstraintException' default error dialog (for example, unique value)
if ((e.Exception) is System.Data.ConstraintException)
{
// ErrorText glyphs show
dataGridView1.Rows[e.RowIndex].ErrorText = "must be unique value";
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "must be unique value";
//...or MessageBox show
MessageBox.Show(e.Exception.Message, "Error ConstraintException",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
//Suppress a ConstraintException
e.ThrowException = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR: dataGridView1_DataError",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
When ever i assign the selected value from my combo box my Winforms application wont close via the controlBox (Minimise, Maximise work but close does not!)
If i comment out the following code it seems to work:
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dataSet1.NewSelectCommand' table. You can move, or remove it, as needed.
this.newSelectCommandTableAdapter.Fill(this.dataSet1.NewSelectCommand);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string databaseName = string.Empty;
databaseName = comboBox1.SelectedItem.ToString();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string databaseName = string.Empty;
if(comboBox1.SelectedItem != null) databaseName = comboBox1.SelectedItem.ToString();
}
I've been trying to follow this MSDN example, and using the code below. However, e.Error is ALWAYS null in RunWorkerCompleted even when an error does occur in SomeMethod();
private void WorkerDoWork(object sender, DoWorkEventArgs e)
{
getMethod = SomeMethod();
}
private void Worker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
var result = ModernDialog.ShowMessage("Error occurred.... " +
e.Result, "ErrorTitle", MessageBoxButton.OK);
}
else if (e.Cancelled)
{
}
Else
{
}
}
Can anyone see what I'm doing wrong?
I can get around it by doing the following but I don't really understand why the example in MSDN is not working for me?
private void WorkerDoWork(object sender, DoWorkEventArgs e)
{
try
{
getMethod = SomeMethod();
}
catch(Exception ex)
{
e.Result = ex;
}
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Result is Exception)
{
var result = ModernDialog.ShowMessage("Error occurred.... " + e.Result, "ErrorTitle", MessageBoxButton.OK);
}
//etc
}
Also, using the second method I can't access the .Message from e.Result. For example, in WorkerDoWork I can use ex.Message
Edit: I've setup the worker to create it's own error and I still get e.Error == null. The variable displayed is a bit faint as CTRL+PrtSc makes it fade
I think the problem is your empty exception block in emailWorkerDoWork(). For the result to be an exception you can't catch the exceptions in your background worker.
So something like this should give you the desired result:
private void emailWorkerDoWork(object sender, DoWorkEventArgs e)
{
int value = 1 / int.Parse("0");
}
I found another SO answer that confirms my suspicion and provides a MSFT reference here.
I know what's wrong, I don't know how to fix it.
I get a
NullReferenceException: Object reference not set to an instance of an object.
I get this error because I have a populated ListBox, when you select a file name in the ListBox the contents of that file are then displayed in a textbox.
Now, I have a depopulate button that clears all the files from the ListBox, if a file is selected, then I get the error.
I want to be able to click the depopulate button and clear both boxes.
The code:
private void DE_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
myScaleTransform2.ScaleX = myScaleTransform2.ScaleX * .9833333333333333333333333333333333333333333333333333333333;
myScaleTransform2.ScaleY = myScaleTransform2.ScaleY * .9833333333333333333333333333333333333333333333333333333333;
lbz.Items.Clear();
}
private void lbz_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
tb1.Text = File.ReadAllText(lbz.SelectedItem.ToString());
}
you will have to check, whether SelectedItem is actually set:
private void lbz_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if( lbz.SelectedItem != null ){
tb1.Text = File.ReadAllText(lbz.SelectedItem.ToString());
} else {
tb1.Text = "No File Selected";
}
}
private void lbz_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if( lbz.SelectedItem != null ){
if(File.Exist(lbz.SelectedItem.ToString())){
tb1.Text = File.ReadAllText(lbz.SelectedItem.ToString());
}
else
{
tb1.Text = "File is not exist in the selected Path";
}
} else {
tb1.Text = "No File Selected";
}
}
Please check weather your list item contain file path or not?