简体   繁体   English

如何将下拉列表的值传递给数据库,反之亦然(ASP.NET C#)

[英]how to pass the value of dropdown to database and vice versa (ASP.NET C#)

如您所见,下拉列表中选定的行值不匹配

As you can see in the photo, the selected row value doesnt match in the dropdown.正如您在照片中看到的,下拉列表中选定的行值不匹配。

I have gridview filled with data from database and when you click a certain row the value from the gridview row will be inserted inside the input box/dropdown, after that the user can edit/manipulate the values and when they click save it will update the selected gridview row with the changes that they made.我有 gridview 填充了数据库中的数据,当您单击某行时,gridview 行中的值将插入输入框/下拉列表中,之后用户可以编辑/操作值,当他们单击保存时,它将更新选择 gridview 行以及他们所做的更改。 The values inside the dropdown list I created are also being fetch from the database.我创建的下拉列表中的值也正在从数据库中获取。 my problem is that when the user click on a certain row, the value of the dropdown list should be the same value with the value of the selected row.我的问题是当用户点击某一行时,下拉列表的值应该与所选行的值相同。 (example: row_1 has the value "cat" when i select the row_1 the dropdown value must change to cat also.) and the other one is that when i choose to change the value inside the selected gridview using the dropdown, it should update(example: using the dropdown, (I change value"cat" to "dog", after i click save the selected griview row should be updated to dog) (例如:row_1 的值为“cat”当我 select 时 row_1 下拉值也必须更改为 cat。)另一个是当我选择使用下拉列表更改所选 gridview 内的值时,它应该更新(示例:使用下拉菜单,(我将值“cat”更改为“dog”,单击保存后,选定的 griview 行应更新为 dog)

this is the gridview code

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
DataKeyNames="CASE_KEY" DataSourceID="SqlDataSource1" Height="250px" 
Width="1109px" BackColor="White" BorderColor="#999999" BorderStyle="None" 
BorderWidth="1px" CellPadding="3" GridLines="Vertical" onrowcommand="GridView1_RowCommand"
OnRowDataBound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="Gainsboro" />
<Columns>
    <asp:buttonfield buttontype="Link" commandname="Select" text="Select" Visible="False" />
    <asp:BoundField DataField="CASE_KEY" HeaderText="CASE_KEY" ReadOnly="True" 
        SortExpression="CASE_KEY" Visible="False" />
    <asp:BoundField DataField="DEPARTMENT_CASE_NUMBER" 
        HeaderText="Department Case #" SortExpression="DEPARTMENT_CASE_NUMBER" />
    <asp:BoundField DataField="DEPARTMENT_NAME" HeaderText="Department" 
        SortExpression="DEPARTMENT_NAME" />
    <asp:BoundField DataField="CHARGE" HeaderText="Charge" 
        SortExpression="CHARGE" />
    <asp:BoundField DataField="LAB_CASE" HeaderText="Lab Case #" 
        SortExpression="LAB_CASE" />
    <asp:BoundField DataField="OFFENSE_DATE" HeaderText="Incident Report Date" 
        SortExpression="OFFENSE_DATE" />
</Columns>

This is the Input fields/dropdown and save这是输入字段/下拉列表并保存

<br />
<asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Names="Arial" 
    Font-Size="Small" Text="Case Details"></asp:Label>
<br />

<table class="style2" >
    <tr>
        <td class="style3" >Department Case #</td>
        <td> <asp:TextBox ID="TextBox1" runat="server" Enabled="False" ontextchanged="btnCancel_Click"></asp:TextBox></td>
    </tr>

    <tr>
         <td class="style3">Department</td>
         <td> 
             <asp:DropDownList ID="DropDownList1" runat="server" 
                  Height="18px" Width="153px" Enabled="False">
             </asp:DropDownList>
         </td>
    </tr>

    <tr> 
         <td class="style3">Charge</td>
         <td>
             <asp:DropDownList ID="DropDownList2" runat="server" 
                 Height="22px" Width="153px" Enabled="False">
             </asp:DropDownList>
         </td>
    </tr>

    <tr>
        <td class="style3">Lab Case #</td>
        <td><asp:TextBox ID="TextBox4" runat="server" Enabled="False"  ontextchanged="btnCancel_Click"></asp:TextBox></td>
   </tr>

   <tr>
       <td class="style3">Incident Report Date</td>
       <td><asp:TextBox ID="TextBox5" runat="server" Enabled="False" ontextchanged="btnCancel_Click"></asp:TextBox></td>
   </tr>

</table>

<asp:TextBox ID="TextBox6" runat="server" Visible="False"></asp:TextBox>
<br />
<asp:Button ID="btnEdit" runat="server" onclick="btnEdit_Click" Text="Edit" />&nbsp;
<asp:Button ID="btnSave" runat="server" onclick="btnSave_Click" Text="Save" Enabled="false"/>&nbsp;
<asp:Button ID="btnCancel" runat="server" onclick="btnCancel_Click" Text="Cancel" Enabled="false"/>
<br />

Code behind背后的代码

 protected void Page_Load(object sender, EventArgs e)
    {
        string connetionString;
        SqlConnection cnn;
       connetionString = @"Data Source=A**SE****D***\MSSQL****;Initial Catalog=****;User 
    ID=****;Password=****";
        cnn = new SqlConnection(connetionString);
        cnn.Open();


        DropDownList1.DataSource = SqlDataSource1;
        DropDownList1.DataBind();
        DropDownList1.DataTextField = "DEPARTMENT_NAME";
        DropDownList1.DataValueField = "DEPARTMENT_CODE";
        DropDownList1.DataBind();

        DropDownList2.DataSource = SqlDataSource1;
        DropDownList2.DataBind();
        DropDownList2.DataTextField = "CHARGE";
        DropDownList2.DataValueField = "OFFENSE_CODE";
        DropDownList2.DataBind();


    }


    protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
       if (e.Row.RowType == DataControlRowType.DataRow)
       {    ///<summary> Change the mouse cursor to Hand symbol to show the user the cell is selectable</summary>
            e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';this.style.cursor='Pointer'";
            e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";

            ///<summary> Attach the click event to each cells</summary>
            e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
        }
    }

    protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
    {
        // If multiple buttons are used in a GridView control, use the
        // CommandName property to determine which button was clicked.
        if (e.CommandName == "Select")
        {
            ///<summary>
            ///Convert the row index stored in the CommandArgument
            ///property to an Integer.
            ///</summary>
            int index = Convert.ToInt32(e.CommandArgument);

            ///<summary>
            /// Retrieve the row that contains the button clicked 
            /// by the user from the Rows collection.
            ///</summary>
            GridViewRow row = GridView1.Rows[index];

            ///<summary> Populate the input box with the value of selected row.</summary>
            GridViewRow gr = GridView1.Rows[index];
            TextBox1.Text = gr.Cells[2].Text;

            **THIS IS WHERE I HAVE A PROBLEM**
            DropDownList1.Text = gr.Cells[3].Text;
            DropDownList2.Text = gr.Cells[4].Text;
            TextBox4.Text = gr.Cells[5].Text;
            TextBox5.Text = gr.Cells[6].Text;
            TextBox6.Text = gr.Cells[1].Text;


        }
    }

protected void btnSave_Click(object sender, EventArgs e)
    { ///<summary> Disabling/Enabling of input fields and button when a certain button is clicked</summary>
        SetEnable(false);

        string connetionString;
        SqlConnection cnn;

        connetionString = @"Data Source=AACSERVERDELL\MSSQL2014;Initial Catalog=VADFS;User ID=vadfs;Password=vadfs";

        cnn = new SqlConnection(connetionString);

        cnn.Open();

        SqlCommand cmd = new SqlCommand("Update TV_LABCASE Set DEPARTMENT_CASE_NUMBER=@DEPARTMENT_CASE_NUMBER,DEPARTMENT_NAME=@DEPARTMENT_NAME,CHARGE=@CHARGE,LAB_CASE=@LAB_CASE,OFFENSE_DATE=@OFFENSE_DATE where CASE_KEY=@CASE_KEY", cnn);
        cmd.Parameters.AddWithValue("@DEPARTMENT_CASE_NUMBER", TextBox1.Text);
        cmd.Parameters.AddWithValue("@LAB_CASE", TextBox4.Text);
          **THIS IS WHERE I HAVE A PROBLEM**
        cmd.Parameters.AddWithValue("@DEPARTMENT_NAME", DropDownList1.ToString());
        cmd.Parameters.AddWithValue("@CHARGE", DropDownList2.ToString());
        cmd.Parameters.AddWithValue("@OFFENSE_DATE", TextBox5.Text);
        cmd.Parameters.AddWithValue("@CASE_KEY", TextBox6.Text);
        cmd.ExecuteNonQuery();
        cnn.Close();
        GridView1.DataBind();    
    }

SQL QUERY SQL 查询

  < asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:VADFSConnectionString %>" SelectCommand="SELECT TOP 10 
    C.CASE_KEY, C.DEPARTMENT_CASE_NUMBER, D.DEPARTMENT_NAME, O.OFFENSE_DESCRIPTION AS CHARGE, LAB_CASE, 
    OFFENSE_DATE, C.DEPARTMENT_CODE,C.OFFENSE_CODE
    FROM TV_LABCASE C
    INNER JOIN TV_DEPTNAME D ON C.DEPARTMENT_CODE = D.DEPARTMENT_CODE
    INNER JOIN TV_OFFENSE O ON C.OFFENSE_CODE = O.OFFENSE_CODE
    ORDER BY C.CASE_DATE DESC"

  ></asp:SqlDataSource>

You need to use SelectedValue Property of DropdownList您需要使用DropdownListSelectedValue属性

You may bind your ddl Like你可以绑定你的ddl Like

DropDownList1.DataTextField = "DEPARTMENT_NAME";
DropDownList1.DataValueField = "DEPARTMENT_NAME";

And

DropDownList2.DataTextField = "CHARGE";
DropDownList2.DataValueField = "CHARGE";

The after In your GridView1_RowCommand() method在你的GridView1_RowCommand()方法之后

 DropDownList1.SelectedValue = gr.Cells[3].Text;
 DropDownList2.SelectedValue = gr.Cells[4].Text;

You need to add a listitem to dropdown lists.您需要将列表项添加到下拉列表中。

// something like this.
ListItem li = new ListItem(gr.Cells[3].Text);

// add the ListItem to the dropdown.
DropDownList1.Items.Add(li);

But you should really be creating a database query that gets case details by ID.但是您确实应该创建一个通过 ID 获取案例详细信息的数据库查询。 the ID is supplied to the query when you select a row in the gridview.当您在 gridview 中的一行 select 时将 ID 提供给查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在ASP.NET C#中将数据从页面传递到用户控件,反之亦然? - How to pass data from page to user control and vise versa in asp.net C#? 如何在c#ASP.NET中传递此值? - How to pass this value in c# ASP.NET? 如何在双向绑定 asp.net 内核中的 blazor C# 的 3 个嵌套组件之间进行通信(从父代到其孙代,反之亦然) - How to communicate between 3 nested components of blazor C# in two-way binding asp.net core (from parent to its grandchild vice versa) C#-从JSON到键值,反之亦然 - C# - JSON to Key Value & vice versa ASP.NET Razor C#SQL数据库下拉列表 - ASP.NET Razor C# SQL Database Dropdown List 如何传递asp.net下拉选择项作为C#中存储过程的输入? - How to pass the asp.net dropdown selected item as an input to a stored procedure in c#? 下拉菜单显示文本作为值的变化asp.net c# - dropdown display text as variation of value asp.net c# C#asp.net下拉列表选择值 - c# asp.net dropdown list select value 使用&lt;%…%&gt;的解决方案,其中asp.net中的runat =“ server”(反之亦然) - Solution for use <% … %> where runat=“server” (or vice versa) in asp.net 如何在asp.net C#Web窗体应用程序中基于下拉列表的选定值填充文本框? - How to populate a textbox based on the selected value of a dropdown list in an asp.net c# web forms application?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM