Weird behavior in combobox C# - c#

I have a weird behavior in my combobox. I have two combobox, one is cboSede an the other is cboGroup. CboSede enable cboGroup. I have already done this in other forms but here I get this message: ArgumentOutOfRangeException was unhandled by user code. The idea is if the user does not choose any value in cboSede then cboGroup is not enabled and in the other hand, if the user choose a valid option in cboSede, cboGroup is enable.
This is my code:
The SelectedIndexChanged of cboSede
private void cboSede_SelectedIndexChanged(object sender, EventArgs e)
{
if (Util.Security.ConexionBD)
{
if (Convert.ToInt32(cboSede.SelectedIndex) == 0 || Convert.ToInt32(cboSede.SelectedIndex) == -1)
{
cboGroup.Enabled = false;
cboGroup.SelectedIndex = 0;
}
else
{
this.FillGroupCombo();
cboGroup.Enabled = true;
}
}
else
MessageBox.Show("Error", "Warning",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
the FillGroupCombo function
private void FillGroupCombo()
{
try
{
Entity.Group objGroup = new Entidad.Group ();
objGroup .IdSede = Convert.ToInt32(cboSede.SelectedValue);
objGroup = Control.Group.ListBySede(objGroup );
if (objGroup != null && objGroup.ListGroup.Count > 0)
{
Entity.Group objMsje = new Entity.Group();
objMsje.IdGroup = -1;
objMsje.Name= "--- Select group ---";
objGroup.ListGroup.Insert(0, objMsje);
}
else
{
Entity.Group objMsje = new Entity.Group();
objMsje.IdGroup = 0;
objMsje.Name= "-- No groups found --";
objGroup.ListGroup.Insert(0, objMsje);
}
Util.Utilitario.FillCombo(objGroup.ListGroup, this.cboGroup, "IdGrupo", "Name");
}
catch (Exception ex)
{
Util.Security.Insert(ex);
Util.Security.SaveLog(ex.Message);
}
}
Any idea about why this happens?

This one
if (Convert.ToInt32(cboSede.SelectedIndex) == 0 || Convert.ToInt32(cboSede.SelectedIndex) == -1)
{
cboGroup.Enabled = false;
cboGroup.SelectedIndex = 0;
}
Will kill the code when SelectedIndex == -1 and you actually have no item in your comboBox (when index = 0, it is OutOfRange)
you can give an if condition if you want
if (cboGroup.Items.Count > 0)
cboGroup.SelectedIndex = 0;
This way, it first check of the comboBox really have anything. And if it doesn't then it won't produce OutOfRange error

Related

compare the items in list in c#

i want to compare the selecteditem of combobox with the selecteditem of other combobox
for this i have registered all the comboboxes in a list and named it "panel1kilist"
now the problem i am facing is that when there are same items in two comboboxes first the messagebox shows "no mattch found" and then it shows "match found" actually it goes to the else statement of inner loop first and then to if statement kindly help
private void button1_Click(object sender, EventArgs e)
{
bool check = false;
bool check1 = false;[![in this image you can see that there are two same items but message is showing "no match found"][1]][1]
try[![after clicking on ok button of message box showing "no match found" this message box shows up][1]][1]
{
for (int i = 1; i < panel1kilist.Count; i++)
{
for (int j = i + 1; j < panel1kilist.Count; j++)
{
if (panel1kilist[i].SelectedItem.ToString() == panel1kilist[j].SelectedItem.ToString())
{
if (check == false)
{
MessageBox.Show("match found");
}
check = true;
}
else
{
if (check1 == false)
{
MessageBox.Show("no match found");
}
check1 = true;
}
}
}
}
catch (System.NullReferenceException)
{
MessageBox.Show("please fill all the boxes first");
}
}
Your question is not really clear but I still try to give you some help. As mentioned in the comments there are several small issues in your code:
1. The outter for-loop
for (int i = 1; i < panel1kilist.Count; i++)
You define i = 1, which means you skip the very first item in your panel1kilist because lists and arrays start at index 0
2. Use of your bool variables
if (panel1kilist[i].SelectedItem.ToString() == panel1kilist[j].SelectedItem.ToString())
{
if (check == false)
{
MessageBox.Show("match found");
}
check = true;
}
else
{
if (check1 == false)
{
MessageBox.Show("no match found");
}
check1 = true;
}
You define your bool variables before starting your for-loops. So whenever you set your variables check and check1 to true, the if conditions check == false and check1 == false will never return true anymore. So you will never get any message except the very first "Match found" and "no match found".
3. My proposed solution
Make use of the foreach-loop and break the loops once you found a match, after the loops just show the message. Code:
var matchFound = false;
foreach (var combobox in panel1kilist)
{
foreach (var comboboxToMatch in panel1kilist.Skip(1))
{
if (combobox.SelectedItem.ToString() == comboboxToMatch.SelectedItem.ToString())
{
matchFound = true;
// Stops the inner loop in case of a match
break;
}
}
// Stops the outer loop in case of a match
if(matchFound)
{
break;
}
}
if(matchFound)
{
MessageBox.Show("match found");
}

Get value of checkbox in Datagridview?

I tried to get value of checked checkbox in DataGridView, so I check if value is true or false:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0 && e.RowIndex != -1)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if ((bool)dataGridView1.Rows[i].Cells["check"].Value == true)
{
dataGridView1.Rows[i].Cells["check"].Value = false;
}
else
{
dataGridView1.Rows[i].Cells["check"].Value = true;
}
button2.Enabled = (counter > 0);
}
}
}
}
It involks an error in line:
if ((bool)dataGridView1.Rows[i].Cells["check"].Value == true)
Second solution:
if (dataGridView1.Rows[i].Cells["check"].Value == null || (bool)dataGridView1.Rows[i].Cells["check"].Value == false)
{
dataGridView1.Rows[i].Cells["check"].Value = true;
counter++;
}
else
{
dataGridView1.Rows[i].Cells["check"].Value = false;
counter--;
}
The code below works, but sometimes checkbox is not checked
I am doing something really similar in a project of mine,
I am only using OnCellValueChanged instead of CellContentClick.
Here's my working line of code
bool completed = Convert.ToBoolean(dgv.Rows[e.RowIndex].Cells[1].Value.ToString());
What is exactly your error? Did you try to see what .Value was in the debugger ?

Additional information: InvalidArgument=Value of '0' is not valid for 'index'

I realize this may look like a duplicate question (I've seen many other questions asking about this error), however I cannot find an answer which explains the issue I'm having. The error is provoked by a call to
invList.SelectedItems[0].Text //invList is a ListView
From what I've read, the error when provoked by this instruction is indicative of attempted access to an empty list (or array?) of selected items in the ListView. However, the ListView I am attempting to access is populated with items at the time of the instruction's execution. Here are the methods in which I issue this instruction:
Method #1: deleteItem
public bool deleteItem()
{
if (invList.SelectedItems.Count == 0) //if no item selected...
{
MessageBox.Show("Error: No item selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
else
{
DialogResult dialogResult = MessageBox.Show(
"Are you sure you want to delete item: " + invList.SelectedItems[0].Text + "?",
"Error", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dialogResult == DialogResult.Yes)
{
for (int i = 0; i < itemRecords.Count; i++)
{
if ((itemRecords[i].id.ToString() == invList.SelectedItems[0].Text) && (itemRecords[i].practice == clinicName))
{
itemRecords.Remove(itemRecords[i]);
listRefresh();
}
}
return true; //return true to indicate that data has been edited
}
return false; // return false to indicate that nothing has changed
}
}
Method #2: updateItem
public bool updateItem()
{
if (invList.SelectedItems.Count == 0) //if no item selected
{
MessageBox.Show("Error: No item selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
else
{
for (int i = 0; i < itemRecords.Count; i++)
{
//if id == the id of the selected item
if((itemRecords[i].id.ToString() == invList.SelectedItems[0].Text) && (itemRecords[i].practice == this.Text))
{
ItemAddition itemAddition = new ItemAddition(itemRecords, itemRecords[i], this);
itemAddition.ShowDialog();
}
}
return true;
}
}
listRefresh:
public void listRefresh()
{
invList.Items.Clear();
loadItems();
}
loadItems:
private void loadItems()
{
foreach (Record r in itemRecords)
{
if (r.practice == clinicName)
invList.Items.Add(r.ToString());
}
}
The error is invoked when the first method is called, but NOT when the second method is called. This inconsistency is the reason for my confusion. Is there some reason this error would only occur in the first method?
Move refreshing method after remove items. If you move item and rebind, then you will lost selection.
for (int i = 0; i < itemRecords.Count; i++)
{
if ((itemRecords[i].id.ToString() == invList.SelectedItems[0].Text) && (itemRecords[i].practice == clinicName))
{
itemRecords.Remove(itemRecords[i]);
//listRefresh();
}
}
listRefresh();
return true;

avoid Row not found or changed error

I have banners on a site. When banner showed then I increment field in DB.
This is code:
public Banner GetBanner(CategoryBanner type)
{
var banners = Database.Banners.Where(b => b.IsPublish.Value &&
b.Category.Value == (int)type &&
b.PeriodShowCountAlready < b.PeriodShowCount || b.IsPublish.Value && b.Category.Value == (int)type &&
b.ShowNext < DateTime.Now);
var count = banners.Count();
if (count != 0)
{
var skip = new Random().Next(banners.Count() - 1);
Banner banner = banners.Skip(skip).FirstOrDefault();
if (banner != null)
{
UpdatePeriodShowCountAlready(banner); // problem is inside this method
if (banner.ShowStart == null)
UpdateShowStartAndEnd(banner);
return banner;
}
}
return null;
}
private void UpdatePeriodShowCountAlready(Banner banner)
{
try
{
if (banner != null)
{
banner.PeriodShowCountAlready++;
if (banner.PeriodShowCountAlready >= banner.PeriodShowCount && banner.ShowNext < DateTime.Now)
{
banner.PeriodShowCountAlready = 0;
banner.ShowStart = null;
banner.ShowNext = null;
}
Database.SubmitChanges();
}
}
catch (Exception ex)
{
ErrorLog.GetDefault(null).Log(new Error(ex));
}
}
And, I get the following error:
System.Data.Linq.ChangeConflictException
Row not found or changed.
This error is simple to reproduce:hold down the F5 is enough for a few seconds.
I understand why this error is occur, but how to rewrite my code properly?
Thanks.

How to Fire an event for another Control while performing DataGridView_CellContentClick?

Actually, I have fired an event on DataGridView_CellContentClick which perform an operation relating to datagridview like changing cell's value But before performing this action i want to make changes(or fire) an another operation on another control i.e. ListView .But this is not gone happens although i place another operation before datagridview's operation. Anybody please help me out.
And my code goes like this:-
private void dGridDeviceList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//DataGridViewCell dcell = dGridDeviceList.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (e.RowIndex >= 0)
{
ListViewItem litem1 = lvInformation.Items.Add("101");
litem1.SubItems.Add(string.Empty);
litem1.SubItems[1].Text = "Connected.";
ListViewItem litem5= lvErrorList.Items.Add("check ");
Cursor = Cursors.WaitCursor;
List<cException> cxp = new List<cException>();
cDeviceModel cdm = new cDeviceModel();
ListViewItem litem = new ListViewItem();
DataGridViewRow drow = new DataGridViewRow();
cDeviceUtility cUtil = new cDeviceUtility();
List<cAction> catn = new List<cAction>();
drow = dGridDeviceList.Rows[e.RowIndex];
cdm = (cDeviceModel)drow.Tag;
if (e.ColumnIndex == 6)
{
if (dGridDeviceList.CurrentCell.Value.ToString() == "Connect")
{
litem1= lvInformation.Items.Add("101");
litem1.SubItems.Add(string.Empty);
litem1.SubItems[1].Text = "Connected.";
//lvInformation.Items.Insert(0, "101");
//lvInformation.Items[0].SubItems.Add("Connected");
}
// connect disconnect button column
if (cdm.IsConnected)
{
ListViewItem litem2 = lvInformation.Items.Add("102");
litem2.SubItems.Add(string.Empty);
litem2.SubItems[1].Text =string.Format("Disconnecting from {0} device.",dGridDeviceList.CurrentRow.Cells["colDeviceName"].Value);
// then disconnect the device
cdm.IsConnected = false;
cdm.DeviceInterface.Disconnect();
dGridDeviceList.Rows[e.RowIndex].Tag = cdm;
dGridDeviceList.Rows[e.RowIndex].Cells[6].Value = "Connect";
dGridDeviceList.Rows[e.RowIndex].Cells[1].Value = img16x16.Images["notconnected"];
dGridDeviceList.Rows[e.RowIndex].Cells[8].Value= 0;
dGridDeviceList.Rows[e.RowIndex].Cells[8].Tag = "Not Connected";
dGridDeviceList.Refresh();
litem2 = lvInformation.Items.Add("103");
litem2.SubItems.Add(string.Empty);
litem2.SubItems[1].Text = string.Format("Disconnected from {0} device.", dGridDeviceList.CurrentRow.Cells["colDeviceName"].Value);
}
else
{
// string test = lvInformation.Items[0].SubItems[1].ToString();
// catn.Add(new cAction { Number = lvInformation.Items.Count+1, Message = string.Format("Trying to connect with {0}", dGridDeviceList.Rows[e.RowIndex].Cells["colDeviceName"].Value) });
//// lvInformation.Items.Clear();
// foreach (cAction Actn in catn)
// {
// litem=lvInformation.Items.Insert(0, (lvInformation.Items.Count + 1).ToString());
// litem.SubItems.Add(catn[catn.Count -1].Message);
// }
// then connect the device
if (!ConnectToDevice(ref drow, out cxp) == true)
{
foreach (cException err in cxp)
{
litem = lvErrorList.Items.Insert(0, err.Number.ToString());
if (err.EType == ErrorType.Error)
{
litem.ImageKey = "error";
}
else if (err.EType == ErrorType.Warning)
{
litem.ImageKey = "warning";
}
else if (err.EType == ErrorType.Information)
{
litem.ImageKey = "information";
}
litem.SubItems.Add(err.Message);
litem.SubItems.Add(err.Source);
}
}
else
{
dGridDeviceList.Rows[e.RowIndex].Cells[0].Value = true;
dGridDeviceList.Rows[e.RowIndex].Tag = drow.Tag;
dGridDeviceList.Rows[e.RowIndex].Cells[6].Value = "Disconnect";
dGridDeviceList.Rows[e.RowIndex].Cells[1].Value = img16x16.Images["connected"];
dGridDeviceList.Rows[e.RowIndex].Cells[8].Value = 0;
dGridDeviceList.Rows[e.RowIndex].Cells[8].Tag = "Ready";
dGridDeviceList.Refresh();
RemoveSelectionRow();
}
}
}
else if (e.ColumnIndex == 7)
{
// view logs button column
pbarMain.Value = 100;
ViewLogs(dGridDeviceList.Rows[e.RowIndex],ref lvAttnLog ,ref lvErrorList);
}
Cursor = Cursors.Arrow;
}
}
considering this is winform
private void buttonCopyContent_Click(object sender, EventArgs e)
{
//do something
}
you can call this event via following line
this.Invoke(new EventHandler(buttonCopyContent_Click));

Categories