简体   繁体   中英

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. 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)

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

  < 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

You may bind your ddl Like

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

And

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

The after In your GridView1_RowCommand() method

 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. the ID is supplied to the query when you select a row in the gridview.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM