How to skip to next item if current variable is null - c#

I have a function that retrieves a list of device names and stores then in a variable. Then the next step is to get info using 1 device name per line and keep going till the loop is complete.
String text = "";
String errors = "";
for (int i = 0; i < collection.Result.Count; i++)
{
deviceNames += collection.Result[i].DeviceName + Environment.NewLine;
getvirtuals.Location = deviceNames;
var virtuals = client.GetKnownVirtuals(getvirtuals, LtmKeyType.VirtualAddressPort);
if (virtuals.Result == null)
{
i++;
getvirtuals.Location = deviceNames;
for (int v = 0; v < virtuals.Result.Count; v++)
{
try
{
LtmKey virtualKey = new LtmKey();
virtualKey.Location = virtuals.Result[v].Location;
virtualKey.LocationType = virtuals.Result[v].LocationType;
virtualKey.Key = virtuals.Result[v].Key;
virtualKey.KeyType = LtmKeyType.VirtualAddressPort;
virtualKey.AdminGroup = admingroupComboBox.Text;
var memberStatus = client.GetMemberStatus(virtualKey);
for (int j = 0; j < memberStatus.Result.Count; j++)
{
VirtualMemberStatus status = memberStatus.Result[j];
text += String.Format("{5},{4},{0},{1},{2},{3}" + Environment.NewLine, status.Member.Address, status.Member.Port, status.EffectiveStatus, status.DesiredStatus, virtualKey.Key.Replace(":", ","), DateTime.UtcNow);
toolStripProgressBar1.PerformStep();
}
}
catch
{
errors += String.Format("{0} Error Code: 2, Error occurred, check device name (case senstive) and admin group. This error may also occur due to connection loss, try again." + Environment.NewLine, DateTime.UtcNow);
}
}
this.allResultsBox.Text = text;
getallstatusButton.Enabled = true;
}
}
The problem that I am running into is that if virtuals is null the tool crashes, instead what I want to do is if virtuals = null I want to move onto the next item from the list. I have tried a if statement but it is not working the way planned, it still comes back as null.

Well this seems like a problem to start with:
if (virtuals.Result == null)
{
i++;
getvirtuals.Location = deviceNames;
for (int v = 0; v < virtuals.Result.Count; v++)
...
If virtuals.Result is null, how do you expect virtuals.Result.Count to work? I suspect you meant:
if (virtuals.Result != null)
However, I suspect you really just want:
// Keep going with the next iteration of the for loop
if (virtuals == null || virtuals.Results == null)
{
continue;
}

If all you want is to go to the next loop iteration if virtuals is null then you want
if (virtuals == null) continue;

How about just inserting:
if(virtuals == null)
continue;
right after the line
var virtuals = client.GetKnownVirtuals(getvirtuals, LtmKeyType.VirtualAddressPort);

Have you tried changing the line:
if (virtuals.Result == null)
to:
if ((virtuals != null) && (virtuals.Result != null))
If this doesn't solve your issue, then you need to indicate what the additional errors are.

if (virtuals.Result == null)
make this
if (virtuals == null)

Related

c# datatable "index was outside the bounds of the array" [duplicate]

Im using the following code to split up a string and store it:
string[] proxyAdrs = linesProxy[i].Split(':');
string proxyServer = proxyAdrs[0];
int proxyPort = Convert.ToInt32(proxyAdrs[1]);
if(proxyAdrs[2] != null)
{
item.Username = proxyAdrs[2];
}
if (proxyAdrs[3] != null)
{
item.Password = proxyAdrs[3];
}
The problem is i am getting
Index was outside the bounds of the array.
When proxyAdrs[2] is not there.
Sometimes proxyAdrs[2] will be there sometimes not.
How can i solve this?
Just check the length of the array returned in your if statement
if( proxyAdrs.Length > 2 && proxyAdrs[2] != null)
{
item.Username = proxyAdrs[2];
}
The reason you are getting the exception is that the split is returning array of size less than the index you are accessing with. If you are accessing the array element 2 then there must be atleast 3 elements in the array as array index starts with 0
You can check the length of array before accessing its element by index.
Change
if(proxyAdrs[2] != null)
{
item.Username = proxyAdrs[2];
}
To
if(proxyAdrs.Length > 2 )
{
item.Username = proxyAdrs[2];
}
Try this:
string[] proxyAdrs = linesProxy[i].Split(':');
string proxyServer = proxyAdrs[0];
int proxyPort = Convert.ToInt32(proxyAdrs[1]);
if(proxyAdrs.Length > 2 && proxyAdrs[2] != null)
{
item.Username = proxyAdrs[2];
}
if (proxyAdrs.Length > 3 && proxyAdrs[3] != null)
{
item.Password = proxyAdrs[3];
}
Check the length of proxyAdrs before you attempt to subscript a potentially non-existent item.
if ( proxyAdrs.Length > 1 ) {
item.Username = proxyAdrs[2];
}
It is that your i which might be lower than the 2 you are trying to set in as index :)
if i >= 2 then you can do all of the follwing:----
if(proxyAdrs[2] != null)
{
item.Username = proxyAdrs[2];
}
if (proxyAdrs[3] != null)
{
item.Password = proxyAdrs[3];
}
}
else I suggest you get out :D
But again, checking proxyAdrs.Lenght would be the best.
There are two options that may help you, depending of whether or not you form incoming data (variable linesProxy):
If you do form incoming data: Always include all parts of the string. In your case, always ensure you have 4 (assuming proxyAdrs[3] is the last) parts by adding additional : between 1st and 3rd values if no value for 2nd is provided. Thus after .Split() operation (ensure you don't activate RemoveEmptyStrings option ) your proxyAdrs[2] will be null and your sample will be fine.
Otherwise: if proxyAdrs[2] is the only part the can be empty following snippet can prevent crashing:
string[] proxyAdrs = linesProxy[i].Split(':');
string proxyServer = proxyAdrs[0];
int proxyPort = Convert.ToInt32(proxyAdrs[1]);
if(proxyAdrs.Length > 3)
{
if(proxyAdrs[2] != null)
item.Username = proxyAdrs[2];
if (proxyAdrs[3] != null)
item.Password = proxyAdrs[3];
}
else
{
if(proxyAdrs[2] != null)
item.Password = proxyAdrs[2];
}
try
{
objCommonDD = new CommonDropDownBLL();
objCommonDDEntity = new CommonDropdownEntity();
//string strState=contextKey.ToString();
string[] contextKeySplit = contextKey.Split('^');
string strState = contextKeySplit[0].ToString();
string strPin = contextKeySplit[1].ToString();
objCommonDDEntity.TableName = "PCOM_PINCODES";
objCommonDDEntity.DeleteField = "";
objCommonDDEntity.TextField = "RTRIM(PIN_CITY_NAME) AS PC_DESC";
objCommonDDEntity.ValueField = "DISTINCT PIN_CITY_CODE AS PC_CODE";
objCommonDDEntity.StrCondition = " AND PIN_COUNTRY_CODE='IND' AND UPPER(PIN_CITY_NAME) LIKE UPPER('" + prefixText + "%') AND PIN_STATE_NAME='" + strState + "' AND PIN_CODE='" + strPin + "' ORDER BY PC_DESC";
DataTable dtCity = new DataTable();
dtCity = objCommonDD.GetData(objCommonDDEntity);
string[] items = new string[dtCity.Rows.Count];
int i = 0;
for (i = 0; i < dtCity.Rows.Count; i++)
{
items.SetValue(dtCity.Rows[i]["PC_DESC"].ToString(), i);
}
return items;
}

ASP.NET/Entity : Issue with my Array Index

I have managed to pull out the FirstorDefault() in the Query, however, some of these address types in the database actually have more than 1 address: therefore, I am trying to build an array of every address regarding each one.
The current code:
int counter = 0;
string queryID = "";
List<string> busAddr = new List<string>();
while (counter != busIDs.Count)
{
queryID = busIDs[counter];
var gathered = (from c in db.tblbus_address where c.BusinessID == queryID && c.AddressTypeID == addrnum select c).ToArray();
int gath = 0;
if ((gathered[gath] as tblbus_address) != null && !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
{
var address = gathered[gath] as tblbus_address;
string test = "";
while (gath != address.Address1.Length)
{
var all = address.Address1;
test += address.Address1.ToString() + ",";
}
busAddr.Add(test);
}
else
{
busAddr.Add("No address for this type exists...");
}
counter++;
gath++;
}
I am receiving an error:
Index was outside the bounds of the array.
at this line:
if ((gathered[gath] as tblbus_address) != null && !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
Can anyone point me in the right direction? I know this structure is the issue but I cannot think how to approach the situation.
You are trying to get the element gathered[gath] when there are no items in gathered. Adding a check for null and Any will help you
if(gathered!=null && gathered.Any()
&& (gathered[gath] as tblbus_address) != null
&& !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
{
...
...
}

c# textbox to datagridview

I want to add the exact value of textbox into datagridview my problem is if i will add another item the last item I add will also change. Here is the print screen of sample problem..
1st try
2nd try
This is my code.
int n = dataGridView3.Rows.Add();
for (int j = 0; j < dataGridView3.RowCount; j++)
{
if (dataGridView3.Rows[j].Cells[1].Value != null && (textBox4.Text == dataGridView3.Rows[j].Cells[4].Value.ToString()))
{
MessageBox.Show("Item Already on List!");
dataGridView3.Rows.Remove(dataGridView3.Rows[n]);
return;
}
else
{
dataGridView3.Rows[j].Cells[1].Value = textBox43.Text;
dataGridView3.Rows[j].Cells[4].Value = textBox4.Text;
dataGridView3.Rows[j].Cells[2].Value = DateTime.Now.ToShortDateString();
dataGridView3.Rows[j].Cells[3].Value = dateTimePicker3.Text;
dataGridView3.FirstDisplayedScrollingRowIndex = n;
dataGridView3.CurrentCell = dataGridView3.Rows[n].Cells[0];
dataGridView3.Rows[n].Selected = true;
}
}
You are looping over the complete array and if it is not yet on the list it goes in to the else part of your if. In that block you assign the current entered values to your row, for every single row you already have.
To fix that I separated the Check for duplicates and the Add part more clearly.
Do notice that if you would have run this through the debugger and stepped on each line of your code (hitting F10 in Visual Studio) you would have spotted this bug easily. Have a look at the blog from Scott Guthrie (among others) http://weblogs.asp.net/scottgu/debugging-tips-with-visual-studio-2010
// check if we already added that one
for (int j = 0; j < dataGridView3.RowCount; j++)
{
if (dataGridView3.Rows[j].Cells[1].Value != null && (textBox4.Text == dataGridView3.Rows[j].Cells[4].Value.ToString()))
{
MessageBox.Show("Item Already on List!");
return;
}
}
// lets add it!
int n = dataGridView3.Rows.Add();
dataGridView3.Rows[n].Cells[1].Value = textBox43.Text;
dataGridView3.Rows[n].Cells[4].Value = textBox4.Text;
dataGridView3.Rows[n].Cells[2].Value = DateTime.Now.ToShortDateString();
dataGridView3.Rows[n].Cells[3].Value = dateTimePicker3.Text;
dataGridView3.FirstDisplayedScrollingRowIndex = n;
dataGridView3.CurrentCell = dataGridView3.Rows[n].Cells[0];
dataGridView3.Rows[n].Selected = true;

For Loop in C# not looping

I have an issue with a Loop that doesn't actually loop. I've posted a simplified version of my code below. Basically, using the NPOI excel library, I have an excel file with data on the first and second sheet, so I need to do a loop to get through both sheets.
Below is what I have done so far, however this only works through the first sheet and then exits. It fails to increment the variable w. As you can see, there are other loops implemented in this code which function fine so I don't get it.
It's been a very long day and perhaps I'm missing something very simple. I could have it placed wrong or something. If anyone else can spot what I might be doing wrong I'd be very grateful :)
public class SalesFileProcessor : ISalesProcessor
{
public List<FTPSalesRow> ProcessSalesFile(string filename)
{
try
{
using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read))
{
int numberOfSheets = 2;
//Loop through sheets - does not work
for (int w = 0; w <= numberOfSheets; w++)
{
HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs);
HSSFSheet sheet = templateWorkbook.GetSheetAt(w);
HSSFRow row = null;
for (int i = 1; i <= sheet.LastRowNum; i++)
{
FTPSalesDetails t = null;
int currentColumn = 0;
try
{
ModelContainer ctn = new ModelContainer();
row = sheet.GetRow(i);
if (row == null)
{
continue;
}
t = new FTPSalesDetails
{
RowNumber = i,
InvoiceDate = GetCellValue(row.GetCell(0)),
CountrySoldIn = GetCellValue(row.GetCell(1)),
NetUnitsSold = GetCellValue(row.GetCell(2)),
Item = GetCellValue(row.GetCell(3)),
ProductCode = GetCellValue(row.GetCell(5)),
};
if (t.ProductCode == null && t.NetUnitsSold == null)
{
return null;
}
int Qty = int.Parse(t.NetUnitsSold);
for (int x = 0; x < Qty; x++)
{
ItemSale ts = new ItemSale
{
ItemID = GetItemID(t.ProductCode),
ManufacturerID = GetManufacturerID("Samsung"),
DateSold = DateTime.Now,
};
ctn.AddToItemSales(ts);
ctn.SaveChanges();
}
}
catch (IndexOutOfRangeException) { }
}
} //End Loop - the one that doesn't work
}
}
catch (IOException exp)
{
throw new FTPSalesFileProcessingException("Could not open the Sales data file", exp);
}
catch (Exception exp)
{
throw new FTPSalesFileProcessingException("An unknown eror occured during processing the file", exp);
}
return null;
}
if (t.ProductCode == null && t.NetUnitsSold == null)
{
return null;
}
I'm going to guess that this is being hit, causing your entire function to exit. If you are trying to exit out of that iteration of the for loop try a break; instead, or a continue as Mike M pointed out in the comments.
For what you say, assuming your variables are all ok that is the loop is not empty... have you checked you're not hiting this line in the first iteration?
if (t.ProductCode == null && t.NetUnitsSold == null)
{
return null;
}
Looking at the code, the only obvious thing sticking out to me is:
HSSFSheet sheet = templateWorkbook.GetSheetAt(w);
HSSFRow row = null;
for (int i = 1; i <= sheet.LastRowNum; i++)
I would guess that sheet.LastRowNum either equals 0 or 1.
Maybe the indexOutOfRangeException is thrown and thats beacuse you have only one iteration, or instead of <= you sholud use <. Does the sheet numbers start with zero ?

Refactor that code ... Controls.Find method

OK, I have a code (see below):
void M1()
{
for (int i = 1; i < 10; i++)
{
Control[] carr = this.Controls.Find("Number" +
(i - 1).ToString() +
"CheckBox", true);
if ((carr != null) && (carr.Length > 0))
{
CheckBox enableCB = carr[0] as CheckBox;
enableCB.Checked = i % 2 == 0 ? true : false; // or any other value
}
}
}
I don't like iteration with using Controls.Find method. Can I replace it with something easier ?
PS: all the NumberXCheckBox (X>=0 and X<=8) presented on the form.
LINQ enabled, .net 3.5, Visual studio 2008.
Instead of searching by name, can you wrap your CheckBox controls in a container that means you can just iterate through the controls in the container?
I would encourage you to introduce a field in your type to keep references to your checkboxes (an array, a list, a dictionary -- you choose.) This way you'll no longer need to use this non-typed and somewhat ugly find-control-by-key-method.
Anyway, if you're still in .NET 2.0 and prefer to use the Find method, you could simplify a little bit your loop:
for (var i = 0; i <= 8; i++)
{
var controls = Controls.Find("Number" + i + "CheckBox", true);
if (controls.Length > 0)
{
var checkBox = controls[0] as CheckBox;
if (checkBox != null)
checkBox.Checked = i%2 == 0;
}
}
The latest non-nullity test on checkbox can probably be omitted.
If you are using 3.5 or otherwise have LINQ available you could do the following
for ( int i = 0; i < 9; i++) {
var control = this.Controls
.Find(String.Format("Number{0}Checkbox", i))
.Cast<CheckBox>()
.FirstOrDefault();
if ( control != null ) {
control.Checked = (i % 2) != 0;
}
}
More linq-y
for (int i = 0; i < 10; i++) {
var c = (from CheckBox c in this.Controls.Find(String.Format(CultureInfo.InvariantCulture, "Number{0}CheckBox", i-1), true)
select c).FirstOrDefault();
if (c != null) {
c.Checked = i % 2 == 0 ? true : false;
}
}
Here's one without linq, but cleaned up the code a little bit.
for (int i = 1; i < 10; i++)
{
Control[] carr = this.Controls.Find("Number" + (i - 1) + "CheckBox", true);
if (carr.Length <= 0) continue;
CheckBox enableCB = carr[0] as CheckBox;
enableCB.Checked = (i % 2) == 0;
}
[Edit: added the Find(..) code to show why you don't have to check for null]
Here's the frameworks internal code for the Find function. I've added a couple of comments in it
public Control[] Find(string key, bool searchAllChildren)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException("key", SR.GetString("FindKeyMayNotBeEmptyOrNull"));
}
// Will always return an ArrayList with zero or more elements
ArrayList list = this.FindInternal(key, searchAllChildren, this, new ArrayList());
// Will always return an Array of zero or more elements
Control[] array = new Control[list.Count];
list.CopyTo(array, 0);
return array;
}

Categories

Resources