1
sqlstr = "select ModuleName,ModuleId,pagename from modules WHERE ParentID='" + parentID + "' AND VIsibility=1 ORDER BY ModuleId";

cmd.CommandText = sqlstr;
cmd.Connection = cn; ;
dr = cmd.ExecuteReader();

while (dr.Read())
{
    menu.Tag = dr["ModuleId"].ToString();
    menu.Text = dr["ModuleName"].ToString();
    menu.Name = dr["pagename"].ToString();
    menu.ToolTipText = dr["pagename"].ToString();
    menuStrip1.Items.Add(menu);
    menuStrip1.Show();
}

cn.Close();
dr.Close();

adding only last item from the query.how to add all the items from the query

SimpleVar
  • 14,044
  • 4
  • 38
  • 60
siva
  • 67
  • 5
  • also u need not close the reader if u r closing the connection, it gets disposed automatically. But you shoud close readers always as a part of good coding habit, which makes sense only if u do it before closing connection – nawfal May 08 '12 at 14:09

3 Answers3

3
while (dr.Read())
{
    // If you don't do this, you are just changing the same
    // ToolStripMenuItem object all the time.
    menu = new ToolStripMenuItem();

    menu.Tag = dr["ModuleId"].ToString();
    menu.Text = dr["ModuleName"].ToString();
    menu.Name = dr["pagename"].ToString();
    menu.ToolTipText = dr["pagename"].ToString();
    menuStrip1.Items.Add(menu);
    menuStrip1.Show();
}
SimpleVar
  • 14,044
  • 4
  • 38
  • 60
1

You have to create a new ToolStripMenuItem in the loop each time. You just keep overwriting properties on the same menu instance.

Seth Flowers
  • 8,990
  • 2
  • 29
  • 42
0

try making a new instance of the menu everytime your read a new row.

Something like this:

 while (dr.Read())
 {
    var menu = new ToolStripMenuItem();

    ...
 }
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73