user838359
user838359

Reputation: 173

Building menu in C#

This is what I've done:

<asp:Menu
    id="Menu1"
    Orientation="Horizontal"
    Runat="Server">
    <StaticMenuStyle
        BackColor="#eeeeee" 
        BorderStyle="solid" 
        BorderColor="Black"
        BorderWidth="1" />
    <DynamicMenuStyle 
        BackColor="#eeeeee" 
        BorderStyle="solid" 
        BorderColor="Black"
        BorderWidth="1" />
</asp:Menu>

In the code behind:

if (!IsPostBack)
{
    DataSet dst = GetMenuData();
    foreach (DataRow masterRow in dst.Tables["Menu"].Rows)
    {
        if ((string)masterRow["parentitemid"] != "NULL" ||
            (string)masterRow["parentitemid"] != "")
        {
            MenuItem masterItem = new MenuItem((string)masterRow["parentitemid"]);
            Menu1.Items.Add(masterItem);
            foreach (DataRow childRow in masterRow.GetChildRows("Menu"))
            {
                MenuItem childItem = new MenuItem((string)childRow["ID"]);
                masterItem.ChildItems.Add(childItem);
            }
        }
    }
}

Basically, I'm trying to bind menu from database. However I get this error:

Unable to cast object of type 'System.DBNull' to type 'System.String'.

This is my database table:

   ID          parentitemid        text                Url
   1            NULL           folder1         /folder1
   2            folder1     WebForm1.aspx   /folder1/WebForm1.aspx
   3            folder1     WebForm2.aspx   /folder1/WebForm2.aspx
   6              null          folder3     /folder3
   7            folder3     WebForm1.aspx   /folder3/WebForm1.aspx
   8            folder3     WebForm2.aspx   /folder3/WebForm2.aspx
   9            folder3     WebForm3.aspx   /folder3/WebFomr3.aspx

So, can you please help me fill the menu.

Upvotes: 0

Views: 228

Answers (1)

mservidio
mservidio

Reputation: 13057

Do something like this when checking for nulls in DataTable

if(dataRow["colName"] != DBNull.Value) 
{ 
    // logic
}

Something like:

if(masterRow["parentitemid"] != DBNull.Value && 
    !string.IsNullOrEmpty(masterRow["parentitemid"].ToString())

See DBNull.Value Field for more information.

Upvotes: 1

Related Questions