如何在网格视图的编辑模式下从下拉列表中获取所选值

时间:2016-04-06 12:01:34

标签: c# asp.net

我想在点击特定行中的编辑按钮时绑定DropDownList。 DropDownList必须显示部门的名称。

但是当我按下模板中的编辑图像按钮时,DropDownList中的选定值始终只是该DropDownList中的第一个值。

ASPX:

<asp:GridView ID="gvEmployeeDetails" runat="server" Width="600px" 
    AutoGenerateColumns="false" ShowFooter="true"
    OnRowDataBound ="RowDataBound"
    onrowdeleting="gvEmployeeDetails_RowDeleting" 
    onrowupdating="gvEmployeeDetails_RowUpdating" 
    onrowcancelingedit="gvEmployeeDetails_RowCancelingEdit" 
    onrowediting="gvEmployeeDetails_RowEditing"
    HeaderStyle-BackColor="#4D4D4D"
    HeaderStyle-ForeColor="White">
    <Columns>            
        <asp:TemplateField HeaderText="Employee ID">              
            <ItemTemplate>
                <asp:Label ID="lblEmpID" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "empid") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>            
                <asp:Label ID="lblEditEmpID" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "empid") %>'></asp:Label>            
            </EditItemTemplate>                  
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:Label ID="lblName" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "name") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>            
                <asp:TextBox ID="txtEditName" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "name") %>'></asp:TextBox>            
            </EditItemTemplate>                    
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Designation">
            <ItemTemplate>
                <asp:Label ID="lblDesignation" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "designation") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>            
                <asp:TextBox ID="txtEditDesignation" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "designation") %>'></asp:TextBox>            
            </EditItemTemplate>                  
        </asp:TemplateField>
        <asp:TemplateField HeaderText="City">
            <ItemTemplate>
                <asp:Label ID="lblCity" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "city") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>            
                <asp:TextBox ID="txtEditCity" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "city") %>'></asp:TextBox>            
            </EditItemTemplate>                   
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Country">
            <ItemTemplate>
                <asp:Label ID="lblCountry" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "country") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>            
                <asp:TextBox ID="txtEditCountry" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "country") %>'></asp:TextBox>            
            </EditItemTemplate>

        </asp:TemplateField>
        <asp:TemplateField HeaderText="Departament">
            <ItemTemplate>
                <asp:Label ID="lblDep" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "department") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>            
                <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
            </EditItemTemplate>                    
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Action">
            <ItemTemplate>
               <asp:ImageButton ID="imgbtnEdit" runat="server" CommandName="Edit" ImageUrl="~/Images/icon-edit.png" Height="32px" Width="32px"/>
               <asp:ImageButton ID="imgbtnDelete" runat="server" CommandName="Delete" ImageUrl="~/Images/Delete.png"/>
            </ItemTemplate>
            <EditItemTemplate>
               <asp:ImageButton ID="imgbtnUpdate" runat="server" CommandName="Update" ImageUrl="~/Images/icon-update.png"/>
               <asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images/icon-Cancel.png"/>
            </EditItemTemplate>                    
        </asp:TemplateField>
    </Columns>            
</asp:GridView>

代码隐藏:

SqlConnection conn = new SqlConnection("Data Source=localhost;Database=testdb;Integrated Security=True");

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindData();
    }
}

protected void BindData()
{       
    DataSet ds = new DataSet();
    DataTable FromTable = new DataTable();
    try
    {
        conn.Open();
        string cmdstr = "select empid, name, designation,city,country,DepartmentDetails.depid as depid, department " +
                        " from EmployeeDetails inner join DepartmentDetails " +
                        " on EmployeeDetails.depid = DepartmentDetails.depid";
        SqlCommand cmd = new SqlCommand(cmdstr, conn);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);           
        adp.Fill(ds);
        cmd.ExecuteNonQuery();
        FromTable = ds.Tables[0];            
        if (FromTable.Rows.Count > 0)
        {
            gvEmployeeDetails.DataSource = FromTable;
            gvEmployeeDetails.DataBind();
        }
        else
        {
            FromTable.Rows.Add(FromTable.NewRow());
            gvEmployeeDetails.DataSource = FromTable;
            gvEmployeeDetails.DataBind();
            int TotalColumns = gvEmployeeDetails.Rows[0].Cells.Count;
            gvEmployeeDetails.Rows[0].Cells.Clear();
            gvEmployeeDetails.Rows[0].Cells.Add(new TableCell());
            gvEmployeeDetails.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            gvEmployeeDetails.Rows[0].Cells[0].Text = "No records Found";
        }
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
    finally
    {
        ds.Dispose();
        conn.Close();
    }
}

protected void gvEmployeeDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    Label lblEmpID = (Label)gvEmployeeDetails.Rows[e.RowIndex].FindControl("lblEmpID");

    conn.Open();
    string cmdstr = "delete from EmployeeDetails where empid=@empid";
    SqlCommand cmd = new SqlCommand(cmdstr, conn);
    cmd.Parameters.AddWithValue("@empid", lblEmpID.Text);
    cmd.ExecuteNonQuery();
    conn.Close();
    BindData();    
}    

protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && gvEmployeeDetails.EditIndex == e.Row.RowIndex)
    {

        DropDownList DropDownList1 = (DropDownList)e.Row.FindControl("DropDownList1");
      //  DropDownList DropDownList1 = (DropDownList)gvr.FindControl("DropDownList1");
        Label lbldep = (Label)gvEmployeeDetails.Rows[e.Row.RowIndex].FindControl("lblDep");

        using (SqlConnection con = new SqlConnection("Data Source=localhost;Database=testdb;Integrated Security=True"))
        {
            using (SqlCommand cmd = new SqlCommand("Select depid, department from DepartmentDetails"))
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                con.Open();
                DropDownList1.DataSource = cmd.ExecuteReader();
                DropDownList1.DataTextField = "department";
                DropDownList1.DataValueField = "depid";
                DropDownList1.DataBind();
               // con.Close();
            }
        }
        // get selected current department
        DropDownList1.SelectedItem.Text = lbldep.Text.ToString();
    }
}

protected void gvEmployeeDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    Label lblEditEmpID = (Label)gvEmployeeDetails.Rows[e.RowIndex].FindControl("lblEditEmpID");
    TextBox txtEditName = (TextBox)gvEmployeeDetails.Rows[e.RowIndex].FindControl("txtEditName");
    TextBox txtEditDesignation = (TextBox)gvEmployeeDetails.Rows[e.RowIndex].FindControl("txtEditDesignation");
    TextBox txtEditCity = (TextBox)gvEmployeeDetails.Rows[e.RowIndex].FindControl("txtEditCity");
    TextBox txtEditCountry = (TextBox)gvEmployeeDetails.Rows[e.RowIndex].FindControl("txtEditCountry");
    DropDownList EditDepid = (DropDownList)gvEmployeeDetails.Rows[e.RowIndex].FindControl("DropDownList1");

    conn.Open();
    string cmdstr = "update EmployeeDetails set name=@name,designation=@designation,city=@city,country=@country, depid=@depid where empid=@empid";
    SqlCommand cmd = new SqlCommand(cmdstr, conn);
    cmd.Parameters.AddWithValue("@empid", lblEditEmpID.Text);
    cmd.Parameters.AddWithValue("@name", txtEditName.Text);
    cmd.Parameters.AddWithValue("@designation", txtEditDesignation.Text);
    cmd.Parameters.AddWithValue("@city", txtEditCity.Text);
    cmd.Parameters.AddWithValue("@country", txtEditCountry.Text);
    cmd.Parameters.AddWithValue("@depid", EditDepid.SelectedValue);
    cmd.ExecuteNonQuery();
    conn.Close();
    gvEmployeeDetails.EditIndex = -1;
    BindData();
}

protected void gvEmployeeDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    gvEmployeeDetails.EditIndex = -1;
    BindData();
}

protected void gvEmployeeDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
    gvEmployeeDetails.EditIndex = e.NewEditIndex;
    BindData();
}

我尝试过很多方法来设置标签文字中的所选项目,但没有运气。有没有人有任何想法?

2 个答案:

答案 0 :(得分:0)

设置DropDownList的选定项可能会造成混淆。你在做什么实际上只是设置所选项目的文本。您实际上并没有告诉DropDownList您想要选择其他项目。

您需要做的是告诉DropDownList您想要选择哪个项目。这是一种方法:

DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText(lbldep.Text));

答案 1 :(得分:0)

我通常在ASPX代码中设置DropDownList的SelectedValue,如下所示

<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("empid") %>'></asp:DropDownList>

即使您将ddl与数据源中的列表绑定在一起,只要在页面加载时绑定了ddl,它就会选择SelectedValue(如果它存在于列表中)。