Objective: To have drop down list select a specific value based on some data on a data table

Issue: Some of the data on the datatable does not have a value and this results in an out of range exception the code is as follows

dtMyDataTable = objMyObject.MyStoredProcedure();

if(dtMyDataTable.Rows.Count > 0)
{
   ddlMyDropDownList = dtMyDataTable.Rows[0]["OptionalField"].ToString();
}

Thank you in advance for any comments, suggestions or recommendations.

有帮助吗?

解决方案 3

For anyone interested this is how I resolved my issue:

       if (dtMyTable.Rows[0]["OptionalField"] != null)
            {
                if (dtMyTable.Rows[0]["OptionalField"].ToString() == "")
                {
                    ddlMyDropDownList .SelectedIndex = 0;
                }
                else
                {
                    ddlMyDropDownList .SelectedValue = dtMyTable.Rows[0]["OptionalField"].ToString();
                }
             }

其他提示

if(dtMyDataTable.Rows.Count > 0)
{
   if(dtMyDataTable.Rows[0]["OptionalField"] != null)
       ddlMyDropDownList = dtMyDataTable.Rows[0]["OptionalField"].ToString();
}

Is ddlMyDropDownList the dropdown list control? If so, you can't assign a string value to a list control. So that might be a problem. See this other answer for how to do that.

That answer should also show you how to prevent against a null value.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top