C# – Get Value from dropdown list and add it to a Gridview

asp.netcdrop-down-menugridview

I have two dropdown lists in asp.net which are generated from a database. When the user selected a value from the first dropdown list, the second dropdown list will be generated based on this value.

I also have a gridview with has a add row, delete and save function. Within each cell of the gridview are textboxes which are self generated by the add row function.

What I want to do is to have a add selected value button from the dropdown list and for the value of the second dropdown list to be added into the first cell of the gridview.

However, if there are muliple gridview rows generated, then a option should appear asking which row the value should be inserted into.

Please can I get some help on this?

Below is the ASP.net

            <asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
            <asp:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <div class="workout">

                    <div class="exerciseDD">
                        <fieldset class="exercise">
                        <legend>Exercise List</legend>
                            <div style="text-align: justify">
                                To begin choose the exercise number you wish to add an exercise too. Then use 
                                the dropdown menu to select the exercise you wish to use in your workout. 
                                Finally click add to insert the exercise into the workout.
                                <br />
                                <br />
                                <asp:Label ID="Label3" runat="server" CssClass="bold" 
                                    Text="Choose an exercise number:"></asp:Label>
                                <br />
                                <asp:DropDownList ID="ExerNo" runat="server">
                                    <asp:ListItem Selected="True">1</asp:ListItem>
                                    <asp:ListItem>2</asp:ListItem>
                                    <asp:ListItem>3</asp:ListItem>
                                    <asp:ListItem>4</asp:ListItem>
                                    <asp:ListItem>5</asp:ListItem>
                                    <asp:ListItem>6</asp:ListItem>
                                    <asp:ListItem>7</asp:ListItem>
                                    <asp:ListItem>8</asp:ListItem>
                                </asp:DropDownList>
                                <br />
                                <br />
                                <asp:Label ID="MuscleGDD" runat="server" CssClass="bold" Text="Muscle Group:"></asp:Label>
                                <br />
                                <asp:DropDownList ID="MuscleDD" runat="server" AutoPostBack="True" 
                                    Height="22px" onselectedindexchanged="MuscleDD_SelectedIndexChanged" 
                                    Width="100%">
                                </asp:DropDownList>
                                <br />
                                <br />
                                <asp:Label ID="Label4" runat="server" CssClass="bold" Text="Exercise Name:"></asp:Label>
                                <br />
                                <asp:DropDownList ID="ExerciseDD" runat="server" AutoPostBack="True" 
                                    Height="22px" onselectedindexchanged="ExerciseDD_SelectedIndexChanged" 
                                    Width="100%">
                                </asp:DropDownList>
                                <br />
                                <br />
                                <asp:Button ID="Add" runat="server" Text="Add Exercise" onclick="Add_Click" />
                                <br />
                                <asp:Label ID="Label5" runat="server" CssClass="bold" 
                                    Text="Exercise Description:"></asp:Label>
                                <br />
                                <asp:Label ID="Exerdes" runat="server"></asp:Label>
                            </div>

                        </fieldset>
                    </div>

                    <div class="createWO">
                        <fieldset class="create">
                            <legend>Create Workout</legend>              
                            <asp:Label ID="LabelUserId" runat="server" Visible="True"></asp:Label>
                            <br />
                            &nbsp;<strong>Workout Name:</strong>&nbsp;<asp:TextBox ID="WorkName" runat="server"></asp:TextBox>
                            <div>
                            <asp:Label ID="CurrentDate" runat="server" />
                                <asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowDeleting="grvWorkout_RowDeleting">
                                    <Columns>
                                    <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
                                    <asp:BoundField DataField="Userid" HeaderText="User ID"  Visible="false"/>
                                    <asp:TemplateField  HeaderText="Exercise Name">
                                        <ItemTemplate>
                                            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Set">
                                        <ItemTemplate>
                                            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Repetition">
                                        <ItemTemplate>
                                            <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Weight">
                                        <ItemTemplate>
                                                <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                                        </ItemTemplate>
                                        <FooterStyle HorizontalAlign="Right" />
                                        <FooterTemplate>
                                            <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" 
                                                onclick="ButtonAdd_Click" />
                                        </FooterTemplate>
                                    </asp:TemplateField>
                                    <asp:CommandField ShowDeleteButton="True" />
                                    </Columns>
                                </asp:gridview>
                                <asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
                                <br />
                                <br />

                </div>

                </div>
            </ContentTemplate>
            </asp:UpdatePanel>
            </asp:Content> 

Below is the Code behind. The code contains the add row, delete and save function. The code also contains the functionality to populate the dropdown lists:

                    private void SetInitialRow()
                    {
                        //Sets the initial row of the gridview
                    }
                    private void AddNewRowToGrid()
                    {
                        //Adds a new row and placing any data back into the gridview
                    }

                    private void SetPreviousData()
                    {
                        //temp save of the dat
                    }

                    protected void Page_Load(object sender, EventArgs e)
                    {
                        if (!Page.IsPostBack)
                        {
                            DataTable MuscleG = new DataTable();
                            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
                            {
                                SqlDataAdapter adapter = new SqlDataAdapter("SELECT [Muscle_id], [MuscleName] FROM [MuscleGroup]", con);
                                adapter.Fill(MuscleG);
                                MuscleDD.DataSource = MuscleG;
                                MuscleDD.DataTextField = "MuscleName";
                                MuscleDD.DataValueField = "Muscle_id";
                                MuscleDD.DataBind();
                            }
                            //MuscleDD.Items.Insert(0, new ListItem("Select Muscle Name", "0"));
                        }

                        if (!Page.IsPostBack)
                        {
                            SetInitialRow();
                        }
                        CurrentDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                    }

                    protected void MuscleDD_SelectedIndexChanged(object sender, EventArgs e)
                    {
                        int muscleid = Convert.ToInt32(MuscleDD.SelectedValue);
                        DataTable exercises = new DataTable();
                        using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
                        {
                            SqlDataAdapter adapter = new SqlDataAdapter("SELECT [Exercise_id], [ExerciseName] FROM [Exercise] WHERE [Muscle_id] = " + muscleid, con2);
                            adapter.Fill(exercises);
                            ExerciseDD.DataSource = exercises;
                            ExerciseDD.DataTextField = "ExerciseName";
                            ExerciseDD.DataValueField = "Exercise_id";
                            ExerciseDD.DataBind();
                        }
                        //ExerciseDD.Items.Insert(0, new ListItem("Select Exercise", "0"));
                    }

                    protected void ExerciseDD_SelectedIndexChanged(object sender, EventArgs e)
                    {
                        int exerciseid = Convert.ToInt32(ExerciseDD.SelectedValue);
                        using (SqlConnection con3 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
                        {
                            con3.Open();
                            string cmdStr = "SELECT [Exercise_id], [ExerDesc] FROM [ExerciseDescription] WHERE [Exercise_id] = '" + exerciseid +"'";
                            SqlCommand Des = new SqlCommand(cmdStr, con3);
                            SqlDataReader reader = Des.ExecuteReader();
                            reader.Read();
                            Exerdes.Text = reader["ExerDesc"].ToString();
                        }
                    }
                    protected void ButtonAdd_Click(object sender, EventArgs e)
                    {
                        AddNewRowToGrid();
                    }

                    protected void Button1_Click(object sender, EventArgs e)
                    {
                        //Saves data in gridview to database
                    }

                    //A method that returns a string which calls the connection string from the web.config
                    private string GetConnectionString()
                    {

                    }

                    //A method that Inserts the records to the database
                    private void InsertRecords(StringCollection sc)
                    {
                        //Inserts the records into the database
                    }
                    protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
                    {
                    }
                    private void SetRowData()
                    {
                        //Set data in temp table
                    }
                    protected void grvWorkout_RowDeleting(object sender, GridViewDeleteEventArgs e)
                    {
                        //Deletes the row
                    }


                     //This function relates to the button I wish to insert the value of the dropdown menu into the gridview.
                    protected void Add_Click(object sender, EventArgs e)
                    {
                        //Add dropdown value
                    }

Best Answer

Here is a quick & dirty sample I made based on your requirement to get you started.

  1. You can select a car make & get selected models
  2. You can add rows to the gridview on button click
  3. You can select the stock model's properties on checkbox click of gridview

Aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="gridTest.aspx.cs" Inherits="WebApplication1.Gridview" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Make:
        <asp:DropDownList ID="ddlMake" runat="server" AppendDataBoundItems="True" AutoPostBack="True"
            OnSelectedIndexChanged="ddlMake_SelectedIndexChanged">
            <asp:ListItem Text=" - Select -" Value=""></asp:ListItem>
        </asp:DropDownList>
        <br />
        Model:
        <asp:DropDownList ID="ddlModels" runat="server">
        </asp:DropDownList>
        <br />
        <br />
        <h2>
            Accessories
            <asp:Button ID="btnAddConsignment" runat="server" OnClick="btnAddConsignment_Click"
                Text="Add Consignment" />
        </h2>
        <asp:GridView ID="gvItems" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="Consignment No.">
                    <ItemTemplate>
                        <%# Container.DataItemIndex+1 %>
                        </ItemTemplate>
                        </asp:TemplateField>

                        <asp:TemplateField HeaderText="Color">

                            <itemtemplate>
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                    </itemtemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Tires">
                            <itemtemplate>
                        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                    </itemtemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="NOS">
                            <itemtemplate>
                        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                    </itemtemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <itemtemplate><asp:CheckBox ID="cbSameAsStock" runat="server" AutoPostBack="True" 
                        oncheckedchanged="cbSameAsStock_CheckedChanged" Text="Same as stock?" /></itemtemplate>
                        </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Codebehind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace WebApplication1
{
    public partial class Gridview : System.Web.UI.Page
    {
        public class Make
        {
            public int Id { get; set; }
            public string Name { get; set; }

            public List<Make> GetMake()
            {
                return new List<Make>() 
                {
                    new Make { Id = 1, Name = "Ford" },
                    new Make { Id = 2, Name = "BMW" },
                    new Make { Id = 3, Name = "Lamborghini" }
                }.ToList();
            }
        }

        public class Models
        {
            public int ModelId { get; set; }
            public int MakeId { get; set; }
            public string Name { get; set; }

            public List<Models> GetModels()
            {
                return new List<Models>()
                {
                    new Models { ModelId=1, MakeId=1, Name="Ford Truck 1"}, 
                    new Models { ModelId=2, MakeId=1, Name="Ford Truck 2"},
                    new Models { ModelId=3, MakeId=1, Name="Ford Truck 3"},
                    new Models { ModelId=4, MakeId=3, Name="Gollarado"},
                    new Models { ModelId=5, MakeId=3, Name="Murcillago"}
                };

            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                // Temporary data fetched through a list. In production you will fetch data from the database
                Make make = new Make();
                ddlMake.DataSource = make.GetMake();
                ddlMake.DataTextField = "Name";
                ddlMake.DataValueField = "Id";
                ddlMake.DataBind();

                if(ViewState["dt"]!=null)
                {    
                    DataTable dt = ViewState["dt"] as DataTable;
                    gvItems.DataSource = dt;
                }
            }

        }

        protected void ddlMake_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Filter second dropdown list
            Models model = new Models();
            ddlModels.DataSource = model.GetModels().Where(s => s.MakeId == int.Parse(ddlMake.SelectedValue));
            ddlModels.DataTextField = "Name";
            ddlModels.DataValueField = "ModelId";
            ddlModels.DataBind();
        }

        protected void btnAddConsignment_Click(object sender, EventArgs e)
        {
            // Bind gridview to temporary data & store inside viewstate
            DataTable dt = null;

            if (ViewState["dt"] == null)
            {
                dt = new DataTable();
                dt.Columns.Add(new DataColumn("Id", typeof(int)));
                dt.Columns.Add(new DataColumn("Color", typeof(string)));
                dt.Columns.Add(new DataColumn("Tires", typeof(string)));
                dt.Columns.Add(new DataColumn("NOS", typeof(string)));
                dt.Columns["Id"].AutoIncrement = true;
                dt.Columns["Id"].AutoIncrementSeed = 1;
            }
            else
                dt = ViewState["dt"] as DataTable;

            DataRow dr = dt.NewRow();
            dt.Rows.Add(dr);

            gvItems.DataSource = dt;
            gvItems.DataBind();

            ViewState["dt"] = dt;


        }

        protected void cbSameAsStock_CheckedChanged(object sender, EventArgs e)
        {
            // Get your checkbox from gridview's selected row
            CheckBox cbTemp = sender as CheckBox;
            if (cbTemp != null)
            {
                // If selected, append selected model name to textboxes
                if (cbTemp.Checked)
                {
                    var selectedModel = ddlModels.SelectedItem.Text;  // your selected car model
                    GridViewRow gr = ((CheckBox) sender).NamingContainer as GridViewRow;
                    if (gr != null)
                    {
                        TextBox txt1 = gr.FindControl("TextBox1") as TextBox;
                        TextBox txt2 = gr.FindControl("TextBox2") as TextBox;
                        TextBox txt3 = gr.FindControl("TextBox3") as TextBox;

                        txt1.Text = "Same as stock "+ selectedModel;
                        txt2.Text = "Same as stock " + selectedModel;
                        txt3.Text = "Same as stock " + selectedModel;
                    }

                }
            }
        }

        }
 }

Sample Car entry screen