【问题标题】:Get Value from dropdown list and add it to a Gridview从下拉列表中获取值并将其添加到 Gridview
【发布时间】:2014-02-15 20:45:19
【问题描述】:

我在 asp.net 中有两个从数据库生成的下拉列表。当用户从第一个下拉列表中选择一个值时,将根据该值生成第二个下拉列表。

我还有一个带有添加行、删除和保存功能的gridview。在 gridview 的每个单元格中都有文本框,这些文本框是由添加行函数自行生成的。

我想要做的是从下拉列表中添加一个选择值按钮,并将第二个下拉列表的值添加到 gridview 的第一个单元格中。

但是,如果生成了多个 gridview 行,则应出现一个选项,询问应将值插入哪一行。

请问我可以得到一些帮助吗?

下面是 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> 

以下是背后的代码。该代码包含添加行、删除和保存功能。该代码还包含填充下拉列表的功能:

                    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
                    }

【问题讨论】:

  • 我们可以看看一些代码吗?
  • @lauCosma 页面的所有代码都已添加。我希望它可以帮助您理解我的问题
  • 那是很多代码。您能否将问题的相关代码提供给我们?
  • @bjb568 对不起,我不应该把所有代码都放进去。我已经删除了大部分代码,但留下了函数名并注释了函数的作用。我要创建的代码后面的最后一个函数。我还留下了生成下拉菜单的功能。所有的 ASP.net 可能都需要。我希望这会更好
  • 你为什么不在下拉的 selectedIndex 更改上生成 gridview 而不是单独的按钮单击?

标签: c# asp.net gridview drop-down-menu


【解决方案1】:

这是我根据您的要求制作的快速而肮脏的示例,以帮助您入门。

  1. 您可以选择汽车品牌并获取选定的车型
  2. 您可以在单击按钮时向 gridview 添加行
  3. 您可以在 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>

代码隐藏

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;
                    }

                }
            }
        }

        }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    相关资源
    最近更新 更多