Wednesday 16 January 2013

Populate Gridview based on listbox selection

Often we need to populate grid based on listbox selections.

For this we have a listbox,one button and grid.

On button click event write following code.
-------------------------------------------
protected void Button2_Click(object sender, EventArgs e)
        {
          
            string Seperator = ""; 
            StringBuilder Builder = new StringBuilder();
            foreach (ListItem li in ListBox1.Items)
            {
                if(li.Selected)
                {
                Builder.Append(Seperator).Append("'"+li.Value+"'");
                Seperator = ",";
                }
            }
            string conStr = @"Server=DEVVM5;Database=Sales;Integrated Security=true";
            SqlConnection conn = new SqlConnection(conStr);
            conn.Open();
            string query = "select * from Product where Name in (" + Builder + ")";
            SqlDataAdapter adp = new SqlDataAdapter(query, conn);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            Gridview1.DataSource = ds;
            Gridview1.AllowPaging = false;
            Gridview1.AllowSorting = false;
            Gridview1.DataBind();
            ViewState["Dataset"] = ds;
            Button1.Visible = true;
          

        }

---------------------------------------

No comments:

Post a Comment