locked
Dropdown in Gridview RRS feed

  • Question

  • User-1499457942 posted

    Hi

      I want asp.net multiselecct dropdown in gridview column like bootstrap multiselect . I want that it should should show only 1 row when clicked then it show the list .

    Is it possible.

    Thanks

    Friday, August 31, 2018 5:24 AM

All replies

  • User839733648 posted

    Hi JagjitSingh,

    According to your description, I’ve made a sample on my side.

    I suggest that you could quote bootstrap-multiselect plugin.

    The key point you should pay attention to is that you may use the function “OnRowDataBound” to bind the selection to your each row.

    For more information, you could refer to the code below.

    .aspx

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.3.min.js"></script>
        <link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
        <link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
        <script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function () {
                $('[id*=ddlDeficiency]').multiselect({
                    includeSelectAllOption: true
                });
            });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="OnRowDataBound">
                    <Columns>
                        <asp:TemplateField HeaderText="ItemInspected">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Eval("Cond_Category") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Deficiency">
                            <ItemTemplate>
                                <asp:ListBox ID="ddlDeficiency" runat="server" SelectionMode="Multiple"></asp:ListBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </div>
        </form>
    </body>
    </html>
    

    Code behind.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;
    protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    DataTable dt = new DataTable();
                    SqlConnection con = new SqlConnection(strCon);
                    con.Open();
                    SqlCommand cmd = new SqlCommand("select Cond_Category from Cond_Category", con);
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    sda.Fill(dt);
                    con.Close();
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
            string strCon = ConfigurationManager.ConnectionStrings["EmployeeManagementConnectionString"].ConnectionString;
            protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
            {
    
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    SqlConnection con = new SqlConnection(strCon);
                    con.Open();
                    ListBox listbox1 = (e.Row.FindControl("ddlDeficiency") as ListBox);
                    SqlCommand cmd = new SqlCommand("select Deficiency from Cond_Deficiency", con);
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    DataTable dt1 = new DataTable();
                    sda.Fill(dt1);
                    con.Close();
                    listbox1.DataSource = dt1;
                    listbox1.DataTextField = "Deficiency";
                    listbox1.DataValueField = "Deficiency";
                    listbox1.DataBind();
                }
            }
    

    result:

    Best Regards,
    Jenifer

    Monday, September 3, 2018 8:58 AM
  • User-1499457942 posted

    Hi jenifer

          How to save the selected records in database field & then retreive in Grid

    Thanks

       

    Monday, September 3, 2018 10:45 AM
  • User839733648 posted

    Hi JagjitSingh,

    I suggest that the key point of saving data is updating the datas in database.

    And the function RowDataBound is still important. 

    I've made a sample on my side, and for more details, you could refer to the code below.

    .aspx

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.3.min.js"></script>
        <link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
        <link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
        <script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>
         <script type="text/javascript">
    
            $(function () {
                $('[id*=listItemBox]').multiselect({
                    includeSelectAllOption: true
                });
            });
    
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView_RowDataBound">
                    <Columns>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="ShowList">
                            <ItemTemplate>
                                <asp:ListBox ID="listItemBox" runat="server" SelectionMode="Multiple">
                                    <asp:ListItem Value="1">Info1</asp:ListItem>
                                    <asp:ListItem Value="2">Info2</asp:ListItem>
                                    <asp:ListItem Value="3">Info3</asp:ListItem>
                                </asp:ListBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
                <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
            </div>
        </form>
    </body>
    </html>

    code behind.

    protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindData();
                }
            }
            string constr = ConfigurationManager.ConnectionStrings["EmployeeManagementConnectionString"].ConnectionString;
            public void BindData()
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("Name");
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT * FROM tb_ListBoxInfo", con))
                    {
                        con.Open();
                        using (SqlDataReader sdr = cmd.ExecuteReader())
                        {
                            while (sdr.Read())
                            {
                                DataRow row = dt.NewRow();
                                row["Name"] = sdr["Name"];
                                dt.Rows.Add(row);
                            }
    
                        }
                    }
                    con.Close();
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
    
            }
    
            protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    string queryname = ((Label)e.Row.Cells[0].FindControl("lblName")).Text;
                    using (SqlConnection con = new SqlConnection(constr))
                    {
                        string myQuery = "SELECT * FROM tb_ListBoxInfo WHERE Name=@Name";
                        SqlCommand cmd = new SqlCommand();
                        cmd.CommandText = myQuery;
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.AddWithValue("Name", queryname);
                        cmd.Connection = con;
                        con.Open();
                        SqlDataReader sdr = cmd.ExecuteReader();
                        if (sdr.HasRows)
                        {
                            while (sdr.Read())
                            {
                                var listboxes = e.Row.FindControl("listItemBox") as ListBox;
                                List<string> selectedValue = new List<string>();
                                if (sdr["info1"].ToString() == "1")
                                {
                                    selectedValue.Add("1");
                                }
                                if (sdr["info2"].ToString() == "1")
                                {
                                    selectedValue.Add("2");
                                }
                                if (sdr["info3"].ToString() == "1")
                                {
                                    selectedValue.Add("3");
                                }
                                foreach (ListItem item in listboxes.Items)
                                {
                                    item.Selected = selectedValue.Contains(item.Value);
                                }
    
                            }
                        }
                        con.Close();
                    }
                }
            }
    
            protected void btnSave_Click(object sender, EventArgs e)
            {
                foreach (GridViewRow row in GridView1.Rows)
                {
                    if (row.RowType == DataControlRowType.DataRow)
                    {
                        string queryname = ((Label)row.FindControl("lblName")).Text;
                        var listboxes = row.FindControl("listItemBox") as ListBox;
                        string info1 = "";
                        string info2 = "";
                        string info3 = "";
                        foreach (ListItem item in listboxes.Items)
                        {
                            if (item.Value == "1")
                            {
                                info1 = item.Selected == true ? "1" : "0";
                            }
                            if (item.Value == "2")
                            {
                                info2 = item.Selected == true ? "1" : "0";
                            }
                            if (item.Value == "3")
                            {
                                info3 = item.Selected == true ? "1" : "0";
                            }
    
                        }
    
                        using (SqlConnection con = new SqlConnection(constr))
                        {
                            string myQuery = "UPDATE tb_ListBoxInfo SET Info1=@Info1,Info2=@Info2,Info3=@Info3 WHERE Name=@Name";
                            SqlCommand cmd = new SqlCommand();
                            cmd.CommandText = myQuery;
                            cmd.CommandType = CommandType.Text;
                            cmd.Parameters.AddWithValue("Name", queryname);
                            cmd.Parameters.AddWithValue("Info1", info1);
                            cmd.Parameters.AddWithValue("Info2", info2);
                            cmd.Parameters.AddWithValue("Info3", info3);
                            cmd.Connection = con;
                            try
                            {
                                con.Open();
                                cmd.ExecuteNonQuery();
                                con.Close();
                                Response.Write("Success");
                            }
                            catch (Exception ex)
                            {
                                Response.Write(ex.Message);
                            }
                        }
                    }
                }
    
            }

    result:

    Best Regards,
    Jenifer

    Wednesday, September 5, 2018 1:18 AM
  • User-1499457942 posted

    Hi Jenifer

    When u have saved u have created separate fields. I want values should be saved only in one field with comma separated and then retrieved data accordingly in Dropdown.

    Thanks

     

    Wednesday, September 5, 2018 4:43 PM
  • User839733648 posted

    Hi JagjitSingh,

    According to your description, I suggest that you could modify parts of the code in code behind.

    You should pay attention to how to read the data in one column field.

    For more information, you could refer to the code below.

    .aspx

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.3.min.js"></script>
        <link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
        <link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
        <script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>
         <script type="text/javascript">
    
            $(function () {
                $('[id*=listItemBox]').multiselect({
                    includeSelectAllOption: true
                });
            });
    
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView_RowDataBound">
                    <Columns>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="ShowList">
                            <ItemTemplate>
                                <asp:ListBox ID="listItemBox" runat="server" SelectionMode="Multiple">
                                    <asp:ListItem Value="1">1</asp:ListItem>
                                    <asp:ListItem Value="2">2</asp:ListItem>
                                    <asp:ListItem Value="3">3</asp:ListItem>
                                </asp:ListBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
                <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
            </div>
        </form>
    </body>
    </html>
    

    code behind.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;
    protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindData();
                }
            }
            string constr = ConfigurationManager.ConnectionStrings["EmployeeManagementConnectionString"].ConnectionString;
            public void BindData()
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("Name");
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT * FROM tb_Select", con))
                    {
                        con.Open();
                        using (SqlDataReader sdr = cmd.ExecuteReader())
                        {
                            while (sdr.Read())
                            {
                                DataRow row = dt.NewRow();
                                row["Name"] = sdr["Name"];
                                dt.Rows.Add(row);
                            }
    
                        }
                    }
                    con.Close();
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
    
            }
    
            protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    string queryname = ((Label)e.Row.Cells[0].FindControl("lblName")).Text;
                    using (SqlConnection con = new SqlConnection(constr))
                    {
                        string myQuery = "SELECT * FROM tb_Select WHERE Name=@Name";
                        SqlCommand cmd = new SqlCommand();
                        cmd.CommandText = myQuery;
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.AddWithValue("Name", queryname);
                        cmd.Connection = con;
                        con.Open();
                        SqlDataReader sdr = cmd.ExecuteReader();
                        if (sdr.HasRows)
                        {
                            while (sdr.Read())
                            {
                                var arr = sdr.GetString(1).Split(',');
                                var listboxes = e.Row.FindControl("listItemBox") as ListBox;
                                foreach (ListItem item in listboxes.Items)
                                {
                                    item.Selected = arr.Contains(item.Value);
                                }
                            }
                        }
                        con.Close();
                    }
                }
    
            }
    
            protected void btnSave_Click(object sender, EventArgs e)
            {
                foreach (GridViewRow row in GridView1.Rows)
                {
                    if (row.RowType == DataControlRowType.DataRow)
                    {
                        string queryname = ((Label)row.FindControl("lblName")).Text;
                        var listboxes = row.FindControl("listItemBox") as ListBox;
                        string Info = string.Empty;
                        foreach (ListItem item in listboxes.Items)
                        {
                            if (item.Selected)
                            {
                                Info += item.Text + ",";
                            }
    
                        }
    
                        using (SqlConnection con = new SqlConnection(constr))
                        {
                            string myQuery = "UPDATE tb_Select SET Info=@Info WHERE Name=@Name";
                            SqlCommand cmd = new SqlCommand();
                            cmd.CommandText = myQuery;
                            cmd.CommandType = CommandType.Text;
                            cmd.Parameters.AddWithValue("Name", queryname);
                            cmd.Parameters.AddWithValue("Info", Info);
                            cmd.Connection = con;
                            try
                            {
                                con.Open();
                                cmd.ExecuteNonQuery();
                                con.Close();
                                Response.Write("Success");
                            }
                            catch (Exception ex)
                            {
                                Response.Write(ex.Message);
                            }
    
                        }
                    }
    
                }
    
            }
    

    result:

    Best Regards,

    Jenifer

    Thursday, September 6, 2018 10:43 AM