Reputation: 171
I am trying to find a key in the namevaluecollection. If the key is found then next piece of code should execute else not.
My Web.config has below configuration:
<Dropdownvalue>
<add key="5" value="Yes" />
<add key="8" value="No" />
<add key="9" value="Maybe" />
</Dropdownvalue>
My code is:
public string getMyId(int MyId)
{
NameValueCollection colMaster = (NameValueCollection)ConfigurationManager.GetSection("Dropdownvalue");
if (colMaster[MyId] != null)
{
//execute code
}
}
When MyId = 9, I get below error for the obvious reason that it is trying to fetch 9th record instead of comparing MyId with Key 9.
System.ArgumentOutOfRangeException: 'Index was out of range.
I know that below code would work perfectly fine:
colMaster["9"]
However, my value changes dynamically so this won't work in my scenario.
Is there a way in namevaluecollection or outside it to access keys from web.config ?
Upvotes: 0
Views: 667
Reputation: 10347
Your problem is that MyID is not a string. Look at the following code:
static void Main(string[] args)
{
var nvc = new NameValueCollection {{"5", "first value"}, {"6", "second value"}, {"9", "third value"}};
Console.WriteLine(nvc["5"]); // first value
Console.WriteLine(nvc[1]); // second value
Console.WriteLine(nvc[3]); // index was out of range
}
nvc[0]
would print first value. Convert MyID to string to make it work.
Upvotes: 0