Am quite new to this, so please help.
I have the following image clicked code.
However, an error will occur if the user does not click on a image.
How can i do an error check to catch that if the user does not click on an image and attempts to proceed, a messagebox will display notifying him to click an image.
Error msg: The error is at "ListViewItem selectedItem = listView1.SelectedItems[0] Error Msg: Invalid Argument = Value of '0' is not valid for 'index
Below is my code:
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int i = e.ProgressPercentage;
object fbUserObject = e.UserState;
if (fbUserObject is DataRow)
{
var fbUser = fbUserObject as DataRow;
var item = new ListViewItem(fbUser["friend_name"].ToString());
item.Tag = fbUser["friend_id"];
item.ImageIndex = i;
listView1.Items.Add(item);
}
else if (fbUserObject is Image)
{
imageList.Images.Add(fbUserObject as Image);
}
}
private void imageClicked(Object sender, System.EventArgs e)
{
ListViewItem selectedItem = listView1.SelectedItems[0];
selectedFBId = selectedItem.Tag as string;
selectedFBName = selectedItem.Text;
DialogResult dialogA = MessageBox.Show("Analyse employee data?", "SOC", MessageBoxButtons.YesNo);
if (dialogA == DialogResult.Yes)
{
TargetEmployee.Text = "Selected Target: " + selectedFBName;
pf.Show();
ThreadPool.QueueUserWorkItem(LoadUserDetails);
}
}
You shouldn't catch an exception, you should handle when there aren't any selected items
if(listView1.SelectedItems.Count == 0)
{
MessageBox.Show(this, "No image");
return;
}
Exceptions should be caught when you don't expect something to happen, if you are aware of a possible issue, you should handle that before it becomes an issue
change your code like this
private void imageClicked(Object sender, System.EventArgs e)
{
if(listView1.SelectedItems.Count < 1)
return;
ListViewItem selectedItem = listView1.SelectedItems[0];
selectedFBId = selectedItem.Tag as string;
selectedFBName = selectedItem.Text;
DialogResult dialogA = MessageBox.Show("Analyse employee data?", "SOC", MessageBoxButtons.YesNo);
if (dialogA == DialogResult.Yes)
{
TargetEmployee.Text = "Selected Target: " + selectedFBName;
pf.Show();
ThreadPool.QueueUserWorkItem(LoadUserDetails);
}
}
You can use a try { } catch { } statement for your error handling.
Once you locate the line of code that generates an exception, you can wrap it into a block like this
try
{
int a = int.Parse("pedantic"); // This throws an error because you cannot convert
}
catch (Exception e)
{
// Handle your error here instead of crashing your program
}
Related
I am very new to c# , and learning to make data entry application,
in my entry form when the user clicks save all the data text boxes are refreshed and saved to database and the text box appears empty to enter gain. This is a continuous process.
Now i want my textbox1 to retain the same value where the user first entered till the form is closed.
Please help me how to achieve this?
i tried this code but the textbox is still empty:
private string value;
private void materiaNumberTextBox_TextChanged(object sender, EventArgs e)
{
var oldValue = value;
value = ((TextBox)sender).Text; // text1.Text
}
here's the code that does while saving:
private void btnsave_Click(object sender, EventArgs e)
{
try
{
String msg = "Confirm Save?";
String caption = "Save Record";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
MessageBoxIcon ico = MessageBoxIcon.Question;
DialogResult result;
result = MessageBox.Show(this, msg, caption, buttons, ico);
if (result == DialogResult.Yes)
{
generateautoID();
this.iP_SpoolsBindingSource.EndEdit();
MessageBox.Show("The Record saved Successfully:" + outputSpoolNoTextBox.Text, "Save_Update",
MessageBoxButtons.OK, MessageBoxIcon.Information);
this.iP_SpoolsTableAdapter.Update(this.pINQCDataSet.IP_Spools);
this.iP_SpoolsTableAdapter.Fill(this.pINQCDataSet.IP_Spools);
//MessageBox.Show("The Record saved Successfully:", "Save_Update",
//MessageBoxButtons.OK, MessageBoxIcon.Information);
this.iP_SpoolsBindingSource.AddNew();
string strStartenddateformat = "dd-MM-yyyy";
materialTypeComboBox.ValueMember = "Tungsten";
unitComboBox.ValueMember = "Mic";
statusComboBox.ValueMember = "Accepted";
cFComboBox.ValueMember = "";
bowOutOfComboBox.ValueMember = "";
ductilityOutofComboBox.ValueMember = "";
finishUOMComboBox.ValueMember = "Mic";
finishTypeComboBox.ValueMember = "Clean";
rejectReason1ComboBox.ValueMember = "";
rejectReason2ComboBox.ValueMember = "";
rejectReason3ComboBox.ValueMember = "";
lotNoTextBox.Text = "0";
dOEDateTimePicker.Format = DateTimePickerFormat.Custom;
dOEDateTimePicker.CustomFormat = strStartenddateformat;
dOEDateTimePicker.Value = DateTime.Now;
dOPDateTimePicker.Format = DateTimePickerFormat.Custom;
dOPDateTimePicker.CustomFormat = strStartenddateformat;
dOPDateTimePicker.Value = DateTime.Now;
}
else
{
return;
}
}
catch (Exception ex)
{
MessageBox.Show("Saving Failed:" + ex.Message.ToString(), "Save",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
here's the image of my form:
You can try the following code to save the first input text in the textbox.
Please use the event textbox_Leave event.
private void button1_Click(object sender, EventArgs e)
{
//Update the database
MessageBox.Show("Update success");
textBox1.Text = textbox; // return to the first input in the textbox
}
int i = 0;
string textbox = "";
private void textBox1_Leave(object sender, EventArgs e)
{
if (i == 0)
{
textbox = textBox1.Text;
i++;
}
}
Result:
Use a data reader to get the values from database and then populate values in textbox using those values.
i have datagridview and column in it,and type is combobox.Combobox value's are used from sql data base.In combobox "Status" i have 5 different item value's.What i want is that when i change item value from combobox and press "save" button ,i want to check which value was before this one(before save) and say:
private void m02BindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
try
{
if (StatusTextBox.Text == "3" && // + want to ask here if previous statusTextBox.text was "1" then to execute lines down if not goes to 'else')
{
DialogResult mbox = MessageBox.Show("do you want to save today's date and time?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
datumOtvaranjaDateTimePicker.Focus();
if (mbox == DialogResult.Yes)
{
datumOtvaranjaDateTimePicker.Value = DateTime.Now;
}
Save();
Refresh();
}
else
{
MessageBox.Show("you cant do that!!!" + Environment.NewLine + "Check what you typed and try again", "Upozorenje", MessageBoxButtons.OK, MessageBoxIcon.Warning);
Refresh();
}
}
catch (Exception)
{
}
}
Look at this other answer
You can handle the ComboBox.Enter event. Then save off the
SelectedItem or SelectedValue to a member variable
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.Enter += comboBox1_Enter;
}
private void comboBox1_Enter(object sender, EventArgs e)
{
m_cb1PrevVal = comboBox1.SelectedValue;
}
private void RestoreOldValue()
{
comboBox1.SelectedValue = m_cb1PrevVal;
}
}
I wrote a search function in my software
when the search result is zero. Its not giving me any pop up windows or any message. How to deal with this situation
My code is as below.
I need any message to be pop up, the moment it shows no data from my table.
private void button4_Click(object sender, EventArgs e)
{
try
{
this.cncInfoTableAdapter.SearchFileName(this.cncDataSet1.CncInfo, textBox1.Text);
}
catch (Exception ex)
{
MessageBox.Show("No records Found " + ex.Message);
}
}
The code of the timer1_Tick (??):
int count = 0;
private void timer1_Tick(object sender, EventArgs e) {
count = cncInfoBindingSource.Count;
label_status.Text = "Records Found: "+count.ToString();
if (count < 2) {
Next_btn.Visible = false;
Previous_btn.Visible = false;
} else {
Next_btn.Visible = true;
Previous_btn.Visible = true;
}
}
Advice please
Thanks
Im having a problem handing an exception in ASP.net WebForms(i'm a beginner)
i want to display the error in the webform using CustomValidator but with no luck, below is my code.
protected void dvEmployeeList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
GridViewRow rowSelect = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int rowindex = rowSelect.RowIndex;
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
try
{
int empID;
empID = int.TryParse(dvEmployeeList.DataKeys[rowindex].Value.ToString(), out empID) ? empID : 0;
oEmployeeBLL.DeleteEmployee(empID);
dvEmployeeList.DataSource = oEmployeeBLL.GetEmployeeList();
dvEmployeeList.DataBind();
}
catch (Exception ex)
{
var delConstrainsVal = new CustomValidator();
delConstrainsVal.IsValid = false;
delConstrainsVal.ErrorMessage = "Update failed: " + ex.Message;
delConstrainsVal.Text = delConstrainsVal.ErrorMessage;
Page.Validators.Add(delConstrainsVal);
}
}
else
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('User cancel!')", true);
}
}
it catch the exception but didnt display the message on the on the form.
Please guide me, thanks!
Validators are meant to validate user input, not to display server errors. You should consider using a simple <asp:Label>.
The reason why the error doesn't appear is probably because validation happens before the control is added.
I am loading the images using the BackgroundThread. I am receving "nullreferenceexception unhandled by user code" after loading all the images into the Listview. What could be the issue? Please let me know.
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
int progress = 0;
string pname;
Image myImage;
max_length = files.Length;
for (int k = 0; k < files.Length; k++)
{
ProgressInfo info = new ProgressInfo();
pname = System.IO.Path.GetFullPath(files[k]);
myImage = Image.FromFile(pname);
info.Image = myImage;
info.ImageIndex = k;
backgroundWorker1.ReportProgress(progress, info);
myImage = null;
}
}
catch (Exception ex)
{
throw ex.InnerException;
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
try
{
//Get image.
ProgressInfo img = e.UserState as ProgressInfo;
//Set image to ListView here.
ImgListView.Images.Add(getThumbnaiImage(ImgListView.ImageSize.Width, img.Image));
fname = System.IO.Path.GetFileName(files[img.ImageIndex]);
ListViewItem lvwItem = new ListViewItem(fname, img.ImageIndex);
lvwItem.Tag = files[img.ImageIndex];
lstThumbNailView.Items.AddRange(new ListViewItem[] { lvwItem });
percent = (int)((float)100 * (float)i / (float)files.Length);
this.progressBar1.Value = (int)percent;
this.label1.Text = "Loading images...";
}
catch (Exception ex)
{
throw ex.InnerException;
}
}
Judging from your comments, you're seeing the error because not all exceptions have an InnerException. If InnerException is null, you will see this problem.
There are several issues at work here though. First, here is the proper try/catch method:
try
{
// Code here
}
catch (Exception ex)
{
// Handle your exception
throw; // Rethrow the same exception, preserving the stack trace (optional)
}
Second, you are likely abusing the purpose of ReportProgress. You should attempt to do all your logic in your backgroundWorker_DoWork, and send the percentage (between 0 and 100) to ReportProgress to update any progress bars.
You may have used the ReportProgress in the way you did to fix a multi-threaded issue. To add items to a ListBox across threads, wrap your code in an anonymous method using the BeginInvoke function
Example:
// Note: I haven't error checked this, and this is only a rough idea of what
// you're trying to do. I'm not even sure of the overall goal here.
this.lstThumbnailView.Invoke((Action)delegate
{
ListViewItem lvwItem = new ListViewItem(name, img.ImageIndex);
ivwItem.Tag = files[img.ImageIndex];
lstThumbNailView.Items.Add(lvwItem);
});
Thanks for the quick response. Here are the changes I made. It seems to be working fine.
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
try
{
ProgressInfo img = e.UserState as ProgressInfo;
LoadImages(img);
this.progressBar1.Value = img.Percent;
this.label1.Text = "Loading images...";
}
catch (Exception ex)
{
throw ex;
}
}
private void LoadImages(ProgressInfo img)
{
ImgListView.Images.Add(getThumbnaiImage(ImgListView.ImageSize.Width, img.Image));
this.lstThumbNailView.Invoke((Action)delegate
{
fname = System.IO.Path.GetFileName(files[img.ImageIndex]);
ListViewItem lvwItem = new ListViewItem(fname, img.ImageIndex);
lvwItem.Tag = files[img.ImageIndex];
lstThumbNailView.Items.Add(lvwItem);
});
}