DataTable.Select() Property: Giving Index Out of Bound Exception - c#

I'm trying to select only those rows which have Parent ID = 0
int predecessor = Parent;
StringBuilder valuePath = new StringBuilder();
valuePath.Append(Parent.ToString());
DataRow[] drPar;
while (true)
{
drPar = dt.Select("MenuID=" + predecessor);
if (drPar != null)
{
if (drPar[0]["ParentID"].ToString().Equals("0"))
break;
}
drPar[0]["ParentID"].ToString().Equals("0") is giving me
Out of Bound exception ..
Help Please !

DataTable.Select does not return null when there's no matching DataRow but an array with Length==0.
But apart from that, why are you using an "infinite" loop for only one statement?
So this should work:
drPar = dt.Select("MenuID=" + predecessor);
if (drPar.Length != 0)
{
if (drPar[0]["ParentID"].ToString().Equals("0"))
{
// ...
}
}

The array drPar must be empty to give this error as it is the only index you use in your code.
Try
if (drPar != null && drPar.Length > 0)

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;
}

How to check whether a record already exists or not via Select command of dataset in c#?

I am trying to tweak the below code for checking whether a record exist or not in the database.
private bool IsAlreadyExist(string LicenseType, int JurisdictionId)
{
LicenceBL lbl = new LicenceBL(0);
DataSet lds = new DataSet();
lbl.FetchForEdit(lds, AgentId, BrokerId);
if (lds.Tables[0].Select('LicenseType='+LicenseType+'and Jurisdiction='+JurisdictionId).Count > 0)
{
return true;
}
else
{
return false;
}
}
It is not working. It throws error... Please help me !!!
Nida, try this:
(1)
if (lds.Tables[0].Select('LicenseType='+LicenseType+'and Jurisdiction='+JurisdictionId).Length > 0) {
}
(2)
LINQ
int count = lds.Tables[0].AsEnumerable()
.Where(x => x["LicenseType"] == YourValue && y => y["Jurisdiction"]==YourValue).ToList().Count;
if (count >0) { // do your stuff}
Select returns an array of rows and Count comes from Linq. So you need to call it as a method Count() not as a property.
if (lds.Tables[0].Select('LicenseType='+LicenseType+
'and Jurisdiction='+JurisdictionId).Count() > 0)
{
Also instead of if/else, following statement, is sufficient:
return lds.Tables[0].Select('LicenseType='+LicenseType+
'and Jurisdiction='+JurisdictionId).Count() > 0;

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))
{
...
...
}

How to find the number of items in a DynamicNodeList?

Is there any property or function for DynamicNodeList which returns the number of list items.
This is my code:
var root = Model.NodeById(id);
var nodes = root.Descendants("ChartItem");
if (nodes.GetLength() > 0)
{
s = s + "<ul>";
}
But GetLength is not a valid function. what should I do?
There is a built in extension method for IEnumerable types called Count(), it does just that, it counts the items :)
See code below:
var root = Model.NodeById(id);
var nodes = root.Descendants("ChartItem");
if (nodes.Count() > 0)
{
s = s + "<ul>";
}
Looking here
http://umbraco.com/follow-us/blog-archive/2011/12/22/umbraco-5-rc1-is-out-today.aspx
I would try (not sure if the null check is required, or if Descendants() returns at least an empty list)
nodes != null && nodes.Count() >0
or
nodes != null && nodes.Any()
Try this code:
var root = Model.NodeById(id);
var nodes = root.Descendants("ChartItem");
int nodesCount = 0;
foreach (var node in nodes)
{
nodesCount += 1;
}
if (nodesCount > 0)
{
s = s + "<ul>";
}

How to Handle the Hashtable null value?

I have a problem while checking a hashtable value. In the code below I am storing 60 values in the hashtable "hash". One of the values is (or can be) Null. I am checking each entry against its corresponding entry in hashtable "hash1", to see if they match each other. If they don't match I want to check if the value in "hash" is Null, but I can't catch it - it's falling through the 'else' part). How can I overcome this problem?
if (hash[j].ToString() == "")
{
NotAnswerQuestionCount++;
}
My Code:
int ctAnsCount=0, flAnsCount=0,NotAnswerQuestionCount=0;
SqlDataAdapter sda =
new SqlDataAdapter("select quesno,[Key] from Answerkey" ,con);
DataSet ds = new DataSet();
sda.Fill(ds);
Hashtable hash = new Hashtable();
for (int i = 0; i < 60; i++)
{
hash[i+1] = ResultsListBox.Items[i].ToString();
}
Hashtable hash1 = new Hashtable();
for (int i = 0; i < 60; i++)
{
hash1[i+1] = ds.Tables[0].Rows[i][1].ToString();
}
for (int j = 1; j <=60; j++)
{
if (hash[j].ToString() != hash1[j].ToString())
{
if (hash[j].ToString() == "")
{
NotAnswerQuestionCount++;
}
//else
flAnsCount++;
}
else
{
ctAnsCount++;
}
}
Test for hash1[i] != null prior to using ToString().
You could try using if(string.IsNullOrEmpty(hash1[i])) or check for null prior to calling ToString().
if (hash[i] != null &&
hash[i].ToString() == "")
{
...
I don't think you mean null, I think you mean empty. You're checking the contents of 'hash', which looks like it is filled from a ListBox, but AFAIK a ListBox item can't be null. Also, you're checking to see if it matches the empty string ("").
How do you know that you have an empty string in the ListBox? Try Trim-ing the value before you check it (i.e. if (hash[j].ToString().Trim() == "") to catch empty strings as well as strings that only contain whitespace. Alternatively output the contents of each ListBox item to debug, bracketed by a delimiter, to check that you've actually got, like so:
foreach (Object o in ResultsListBox.Items) {
Debug.WriteLine("'" + o.ToString() + "'");
}
From C# 6 and onwards you can use the Null-conditional operator ?.
if (hash[i]?.ToString() == "") { ...
If you want to check whether a Hash Object is null or size is zero.
I think you can do like this
if (hash!= null || hash.Keys.Count==0) { blah }
Thank you.

Categories

Resources