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 ?
Your problem is that MyID is not a string. Look at the following code:
nvc[0]would print first value. Convert MyID to string to make it work.