【问题标题】:Get the drop down list selected item on grid row command event获取网格行命令事件上的下拉列表选定项
【发布时间】:2014-07-22 08:01:00
【问题描述】:

我有一个ma​​nage Customer表格和网格视图customer

我正在尝试更新网格记录。我想当我点击编辑链接记录时显示在表格中。

我正在尝试在 Grid_Row_command 事件上执行此操作。

我在文本框中获取记录,但无法获取选定的下拉记录。

请告诉我该怎么做。

这是我的表格和 Gridview 的快照。

.

这是我的代码-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mspl.Web.MobileTracking.BL;
using Mspl.MobileTracking.Model;

namespace Mspl.Web.MobileTracking.UserControls
{
    public partial class ManageCustomers : System.Web.UI.UserControl
    {
        Utility utility;
        string result = string.Empty;
        User user = new User();
        CustomerBL customerBL;
        Customer Customer = new Customer();
        CustomerBL Customers = new CustomerBL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindCountry();
                BindCustomer();
            }

            lblMessage.Text = string.Empty;
        }

        private void BindStates()
        {
            utility = new Utility();
            var states = utility.GetStates(ddlCountry.SelectedItem.Value);
            ddlState.DataSource = states;
            ddlState.DataTextField = "Name";
            ddlState.DataValueField = "ID";
            ddlState.DataBind();
            ddlState.Items.Insert(0, "--Select--");
        }

        private void BindCountry()
        {
            utility = new Utility();
            var countries = utility.GetCountries();
            ddlCountry.DataSource = countries.ToList<Country>();
            ddlCountry.DataTextField = "Name";
            ddlCountry.DataValueField = "ID";
            ddlCountry.DataBind();
            ddlCountry.Items.Insert(0, "--Select--");
        }

        private void BindDistricts()
        {
            utility = new Utility();
            var districts = utility.GetDistricts(ddlState.SelectedItem.Value);
            ddlDistrict.DataSource = districts;
            ddlDistrict.DataTextField = "Name";
            ddlDistrict.DataValueField = "ID";
            ddlDistrict.DataBind();
            ddlDistrict.Items.Insert(0, "--Select--");
        }

        private void BindCustomer()
        {
            gvCustomer.DataSource = Customers.GetAllCustomers();
            gvCustomer.DataBind(); 
        }


        protected void gvCustomer_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "displayCustomer")
            {
                GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
                hfCustomerId.Value = Convert.ToString(e.CommandArgument);
                Label lblCName = (Label)row.FindControl("lblCustomerName");
                txtCustomerName.Text = lblCName.Text;
                Label lblAdd1 = (Label)row.FindControl("lblAddressLine1");
                txtAddressline1.Text = lblAdd1.Text;
                Label lblAdd2 = (Label)row.FindControl("lblAddressLine2");
                txtAddressline2.Text = lblAdd2.Text;
                Label lblPhone = (Label)row.FindControl("lblPhone");
                txtPhone.Text = lblPhone.Text;
                Label lblMobile = (Label)row.FindControl("lblMobile");
                txtMobileNumber.Text = lblMobile.Text;
                Label lblCountry = (Label)row.FindControl("lblCountry");
                ddlCountry.SelectedIndex = Convert.ToInt32(lblCountry.Text);
                Label lblState = (Label)row.FindControl("lblState");
                ddlState.SelectedIndex = Convert.ToInt32(lblState.Text);
                Label lblDistrict = (Label)row.FindControl("lblDistrict");
                ddlDistrict.SelectedIndex = Convert.ToInt32(lblDistrict.Text);
                Label lblCity = (Label)row.FindControl("lblCity");
                txtCity.Text = lblCity.Text; 
            }
        }

        protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindStates();
        }

        protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindDistricts();
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            Customer customers = new Customer();
            user = Session["UserDetails"] as User;
            customers.ID = hfCustomerId.Value;
            customers.Name = txtCustomerName.Text;
            customers.Mobile = txtMobileNumber.Text;
            customers.Phone = txtPhone.Text;
            customers.AddressLine1 = txtAddressline1.Text;
            customers.AddressLine2 = txtAddressline2.Text;
            customers.Country = ddlCountry.SelectedItem.Value;
            customers.State = ddlState.SelectedItem.Value;
            customers.District = ddlDistrict.SelectedItem.Value;
            customers.City = txtCity.Text;
            customers.UpdatedBy = user.ID;

            if (Page.IsValid)
            {
                var result = Customers.UpdateCustomer(customers);
                if (result == "Success")
                    lblMessage.Text = "Sucessfully Updated";
                else
                    lblMessage.Text = "Already Exists";

                BindCustomer();
                refreshControls();
            }

            setFormstatus(0);

        }
    }
}

我的网格代码-

<asp:HiddenField ID="hfCustomerId" runat="server" />
                <asp:GridView ID="gvCustomer" runat="server" AutoGenerateColumns="False" CellPadding="4"
                    EnableModelValidation="True" ForeColor="#333333" GridLines="Both" 
                    onrowcommand="gvCustomer_RowCommand" onrowcreated="gvCustomer_RowCreated">
                    <AlternatingRowStyle BackColor="White" />
                    <EditRowStyle BackColor="#2461BF" />
                    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle HorizontalAlign="Left" CssClass="normalText" BackColor="#507CD1" Font-Bold="True"
                        ForeColor="White" />
                    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                    <RowStyle BackColor="#EFF3FB" />
                    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                    <Columns>
                        <asp:TemplateField HeaderText="Id">
                            <ItemTemplate>
                                <asp:Label ID="lblCustomerId" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label ID="lblCustomerName" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="AddressLine1">
                            <ItemTemplate>
                                <asp:Label ID="lblAddressLine1" runat="server" Text='<%# Bind("AddressLine1") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="AddressLine2">
                            <ItemTemplate>
                                <asp:Label ID="lblAddressLine2" runat="server" Text='<%# Bind("AddressLine2") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Mobile">
                            <ItemTemplate>
                                <asp:Label ID="lblMobile" runat="server" Text='<%# Bind("Mobile") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                         <asp:TemplateField HeaderText="Phone">
                            <ItemTemplate>
                                <asp:Label ID="lblPhone" runat="server" Text='<%# Bind("Phone") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Country">
                            <ItemTemplate>
                                <asp:Label ID="lblCountry" runat="server" Text='<%# Bind("Country") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="State">
                            <ItemTemplate>
                                <asp:Label ID="lblState" runat="server" Text='<%# Bind("State") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="District">
                            <ItemTemplate>
                                <asp:Label ID="lblDistrict" runat="server" Text='<%# Bind("District") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="City">
                            <ItemTemplate>
                                <asp:Label ID="lblCity" runat="server" Text='<%# Bind("City") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:LinkButton ID="linkName" runat="server" Text="Edit" CommandName="displayCustomer"  CommandArgument='<%# Eval("ID")%>' >
                                </asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>

【问题讨论】:

  • 您没有获得所有下拉菜单的值?还添加你的html代码
  • 仅限 ddl 国家/地区...
  • 您的 lblCountry.Text 中有哪些值?所选国家/地区 ID 或国家/地区名称?
  • 获取国家名称
  • 您是否在网格视图中将 用于下拉列表?

标签: c# asp.net gridview


【解决方案1】:

试试这个,

ddlCountry.SelectedIndex = ddlCountry.Items.IndexOf
(ddlCountry.Items.FindByText(lblCountry.Text);

【讨论】:

  • 这里的状态是什么?
  • 那就试试这个ddlCountry.SelectedItem.Text = lblCountry.Text;
  • 我得到的是国家的选定索引,而不是州和地区的索引。
  • 你尝试哪种方法?
【解决方案2】:

你已经找到下拉列表,首先用你的状态列表填充它,然后使用 喜欢

ddlState.Items.FindbyText(lblState.text).Selected=true;

你可以这样试试

if (e.commandname == "displayCustomer") {
    GridViewRow gv = (GridViewRow)((Control)e.CommandSource).NamingContainer;
    label lblCountry = gv.findControl("lblCountry");
    label lblState = gv.findcontrol("lblState");
    label lblDistrict = gv.findcontrol("lblDistrict");


    //call function to fill your country


    ddlCountry.items.finbytext(lblCountry.text).selected = true;

    //call function to fill states based on ddlcountry selected item

    ddlState.items.finbytext(lblState.text).selected = true;


    //call function to fill district based on ddlStateselected item

    ddlDistrict.items.finbytext(lblDistrict.text).selected = true;



}

【讨论】:

  • 出现错误-对象引用未设置为对象的实例。
  • 首先为国家做,然后根据国家填写州下降,然后根据州填写地区。
  • 给出错误 - ddlcountry.items.findbyvalue(lblcountry.text).selected=true;
【解决方案3】:

实际上,您不需要执行所有这些代码。

Label lblCountry = (Label)row.FindControl("lblCountry");
ddlCountry.SelectedIndex = Convert.ToInt32(lblCountry.Text);
Label lblState = (Label)row.FindControl("lblState");
ddlState.SelectedIndex = Convert.ToInt32(lblState.Text);
Label lblDistrict = (Label)row.FindControl("lblDistrict");
ddlDistrict.SelectedIndex = Convert.ToInt32(lblDistrict.Text);

一种更好的方法是:

<asp:LinkButton ID="linkName" runat="server" Text="Edit" CommandName="displayCustomer"  CommandArgument='<%# Eval("ID")%>' ></asp:LinkButton>



public void gvCustomer_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        // Here "i" is the id(CommandArgument='<%# Eval("ID")%>') of the record 
        //coming from the link button.
        int i = Convert.ToInt32(e.CommandArgument);

        if (e.CommandName == "Edit1")
        {

            // Execute your Database query with where condition for "i" 
            // and fetch the value in data reader. The Query will be like 
            // Select * from Table_Name where ID = i
            // This will get you the particular record for that ID only

            while (dr.Read())
            {
                DrpCountry.SelectedItem.Value = dr["CountryID"].ToString();
                DrpState.SelectedItem.Value = dr["StateID"].ToString();
                DrpDistrict.SelectedItem.Value = dr["DistrictID"].ToString();
            }
        }
    }

【讨论】:

  • 我必须在哪里调用这个方法?
  • 使用数据库查询获取所有记录,而不是单个记录。
  • 不只是获取所选行的记录,例如“select * from Table_Name where Id=i”。检查我的更新答案
【解决方案4】:

从下拉列表中选择特定值

ddlCountry.SelectedIndex=ddlCountry.Items.IndexOf(ddlCountry.Items.FindByText(lblCountry.Text));

【讨论】:

  • 获取国家/地区的记录,而不是获取州和地区的记录。
【解决方案5】:

更新:

问题是,当您在 Country DropDown 中选择值时,它已经被填写,而您的州和城市 DropDowns 未填写,这就是它们不起作用的原因,

    protected void gvCustomer_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "displayCustomer")
        {
            GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
            hfCustomerId.Value = Convert.ToString(e.CommandArgument);
            Label lblCName = (Label)row.FindControl("lblCustomerName");
            txtCustomerName.Text = lblCName.Text;
            Label lblAdd1 = (Label)row.FindControl("lblAddressLine1");
            txtAddressline1.Text = lblAdd1.Text;
            Label lblAdd2 = (Label)row.FindControl("lblAddressLine2");
            txtAddressline2.Text = lblAdd2.Text;
            Label lblPhone = (Label)row.FindControl("lblPhone");
            txtPhone.Text = lblPhone.Text;
            Label lblMobile = (Label)row.FindControl("lblMobile");
            txtMobileNumber.Text = lblMobile.Text;
            Label lblCountry = (Label)row.FindControl("lblCountry");


            // -------------------------- changed code --------------------------

            ddlCountry.SelectedIndex = ddlCountry.Items.IndexOf(ddlCountry.Items.FindByText(lblCountry.Text))


            // at this point country should be filled and selected, so we can bind and select appropriate state
            BindStates();

            Label lblState = (Label)row.FindControl("lblState");
            ddlSate.SelectedIndex = ddlSate.Items.IndexOf(ddlSate.Items.FindByText(lblState.Text))

            // at this point states should be filled and selected, so we can bind and select appropriate District
            BindDistricts();


            Label lblDistrict = (Label)row.FindControl("lblDistrict");
            ddlDistrict.SelectedIndex = ddlDistrict.Items.IndexOf(ddlDistrict.Items.FindByText(lblDistrict.Text))

            //---------------------------------------------------------------------

            Label lblCity = (Label)row.FindControl("lblCity");
            txtCity.Text = lblCity.Text; 
        }
    }

正如您在 cmets 中提到的,GridView 中的 Country 列实际上是国家名称而不是国家 ID。当您将此 lblCountry.Text 转换为 int32 并尝试设置索引时。这应该给出我想的错误。

您目前采用的方法似乎不对,更好的方法可能是将网格中记录的ID保存在一些HiddenField中,然后在RowCommand上,从@中选择ID 987654330@,从数据库中获取数据,然后加载到您的输入框中。

无论如何,如果想解决办法,请将CountryID 和您的国家/地区名称一起保存在HiddenField 中,

<asp:TemplateField HeaderText="Country">
    <ItemTemplate>
        <asp:Label ID="lblCountry" runat="server" Text='<%# Bind("Country") %>'></asp:Label>
        <asp:HiddenField ID="hfCountryID" runat="server" Value='<%# Bind("CountryID") %>'></asp:HiddenField>
    </ItemTemplate>
</asp:TemplateField>

然后你可以使用这个CountryID设置DropDown

var hfCountryID = row.FindControl("hfCountryID") as HiddenField;
ddlCountry.SelectedValue = Convert.ToInt32(hfCountryID.Text); 

另一种解决方法是使用国家名称查找项目并选择它,

ddlCountry.SelectedIndex = ddlCountry.Items.IndexOf(ddlCountry.Items.FindByText(lblCountry.Text));

【讨论】:

  • 数据库中没有国家/地区 ID 字段。
  • 然后你可以选择国家名称选项
  • 我在国家获得价值,而不是在州和地区获得价值。
  • 您必须在开始时进行绑定...目前您没有为州和地区进行绑定
  • 我在选定的索引上绑定州和地区
【解决方案6】:

您只需要创建一个函数来获取国家或州的 ID 或其他 那么你可以这样做:

ddlCounty.SelectedValue=CountyID.ToString();

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 2022-01-21
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多