从UpdateView中的GridView中的下拉列表中获取选定的值 [英] Getting a selected value from the drop down list inside a GridView on Update

查看:57
本文介绍了从UpdateView中的GridView中的下拉列表中获取选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个GridView,每行都有Edit按钮。单击后,SAPLeader列将变为下拉列表,用户可以在其中选择值。编辑按钮变为更新 - 获取null!出于某种原因,SAPLeader字段未显示我的更新。





I have a GridView, each row has Edit button. After it's clicked, SAPLeader column turns into a drop down list where users can select value. Edit button becomes Update - Getting a null! For some reason the SAPLeader field is not showing my update.


  protected void Page_Load(object sender, EventArgs e)
{
    lblMsg.Text = "";
    if (!Page.IsPostBack)
    {

        gvAccountStaff.DataBind();
        BindSubjectData();
    }
}
call to bind gridview
public class DropDownData
{
    public DropDownData(int id, string displaytext)
    {
        iD = id;
        text = displaytext;
    }
    int iD;
    public int ID
    {
        get { return iD; }
        set { iD = value; }
    }
    string text;
    public string Text
    {
        get { return text; }
        set { text = value; }
    }
}
protected void gvAccountStaff_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Control ctrl = e.Row.FindControl("ddlType");
        if (ctrl != null)
        {
            conn.Close();
            DropDownList dd = ctrl as DropDownList;
            List<DropDownData> lst = new List<DropDownData>();
            SqlCommand cmd = new SqlCommand("SELECT ID, LastName, FirstName FROM CMS_DC_AccountStaff WHERE PeopleManager = 'TRUE'");
            SqlDataReader myReader = null;
            cmd.Connection = conn;
            conn.Open();
            myReader = cmd.ExecuteReader();
            while (myReader.Read())
            {
                DropDownData cust1 = new DropDownData(Convert.ToInt16(myReader["ID"].ToString()), (myReader["LastName"].ToString() + ", " + myReader["FirstName"].ToString()));
                lst.Add(cust1);
            }
            dd.DataTextField = "Text";
            dd.DataValueField = "ID";
            dd.DataSource = lst;
            dd.DataBind();
        }
    }
}  protected void gvAccountStaff_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    bool IsUpdated = false;
    //getting key value, row id
    int ID =
    Convert.ToInt32(gvAccountStaff.DataKeys[e.RowIndex].Value.ToString());
    //getting row field details

    TextBox LastName =
    (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtLastName");
    TextBox FirstName = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtFirstName");
    TextBox Birthday = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtBirthday");
    TextBox NetID = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtNetID");
    TextBox PersonelNumber = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtPersonelNumber");
    TextBox EDSAnniversary = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtEDSAnniversary");
    TextBox PeopleManager = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtPeopleManager");
    TextBox SAPLeader = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtSAPLeader");
    TextBox HomeAddress = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtHomeAddress");
    TextBox HomeCity = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtHomeCity");
    TextBox HomeState = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtHomeState");
    TextBox HomeZip = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtHomeZip");
    TextBox WorkAddress = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtWorkAddress");
    TextBox WorkMailstop = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtWorkMailstop");
    TextBox WorkCity = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtWorkCity");
    TextBox WorkState = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtWorkState");
    TextBox WorkZip = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtWorkZip");

    //   TextBox Grade = (TextBox)gvSubDetails.Rows[e.RowIndex].FindControl("txtGrade");
    using (SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLStaffingConn"].ConnectionString))
    {

        using (SqlCommand cmd = new SqlCommand())
        {
            Control ctrl2 = gvAccountStaff.FindControl("ddlType") as DropDownList;
          DropDownList ddl1 = (DropDownList)ctrl2;
            //here i'd added "@" for continuous string in new line
            cmd.CommandText = @"UPDATE CMS_DC_AccountStaff SET LastName=@LastName, FirstName=@FirstName, Birthday=@Birthday, NetID=@NetID,  PersonelNumber=@PersonelNumber, EDSAnniversary=@EDSAnniversary, PeopleManager=@PeopleManager, SAPLeader=@SAPLeader, HomeAddress=@HomeAddress, HomeCity=@HomeCity, HomeState=@HomeState, HomeZip=@HomeZip, WorkAddress=@WorkAddress, WorkMailstop=@WorkMailstop, WorkCity=@WorkCity, WorkState=@WorkState, WorkZip=@WorkZip WHERE ID=@Id";
            cmd.Parameters.AddWithValue("@Id", ID);
            cmd.Parameters.AddWithValue("@LastName", LastName.Text);
            cmd.Parameters.AddWithValue("@FirstName", FirstName.Text);
            cmd.Parameters.AddWithValue("@Birthday", Birthday.Text);
            cmd.Parameters.AddWithValue("@NetID", NetID.Text);
            cmd.Parameters.AddWithValue("@PersonelNumber", PersonelNumber.Text);
            cmd.Parameters.AddWithValue("@EDSAnniversary", EDSAnniversary.Text);
            cmd.Parameters.AddWithValue("@PeopleManager", PeopleManager.Text);
            cmd.Parameters.AddWithValue("@SAPLeader",  SAPLeader.Text);
            cmd.Parameters.AddWithValue("@HomeAddress", HomeAddress.Text);
            cmd.Parameters.AddWithValue("@HomeCity", HomeCity.Text);
            cmd.Parameters.AddWithValue("@HomeState", HomeState.Text);
            cmd.Parameters.AddWithValue("@HomeZip", HomeZip.Text);
            cmd.Parameters.AddWithValue("@WorkAddress", WorkAddress.Text);
            cmd.Parameters.AddWithValue("@WorkMailstop", WorkMailstop.Text);
            cmd.Parameters.AddWithValue("@WorkCity", WorkCity.Text);
            cmd.Parameters.AddWithValue("@WorkState", WorkState.Text);
            cmd.Parameters.AddWithValue("@WorkZip", WorkZip.Text);

            cmd.Connection = sqlCon;
            sqlCon.Open();
            IsUpdated = cmd.ExecuteNonQuery() > 0;
            sqlCon.Close();
        }
    }
    if (IsUpdated)
    {
        lblMsg.Text = "'" + FirstName.Text + " " + LastName.Text + "' Account Staff updated successfully!";
             lblMsg.ForeColor = System.Drawing.Color.Green;
    }
    else
    {
        lblMsg.Text = "Error while updating '" + FirstName.Text + " " + LastName.Text + "' subject details";
            lblMsg.ForeColor = System.Drawing.Color.Red;
    }
    gvAccountStaff.EditIndex = -1;
    BindSubjectData();
}



aspx代码:< asp:TemplateField HeaderText =SAPLeader>



< asp:DropDownList runat =serverDataValueField =CatalogDataTextField =ShowID =ddlTypeAutoPostBack =true/>

<% - - < asp:TextBox ID =txtSAPLeaderText ='<%#Eval(SAPLeader)%>'

runat =server/> - %>



问题是当我显示我的datagridview gvAccountStaff时,我有一个名为SAPLeader的列,它有一个下拉列表。当我在列表中选择一个名称时会出错:对象引用未设置为对象的实例。 SAPLeader字段为空。我尝试用不兼容的ddl1.SelectedValue替换@SAPLeader。我将不胜感激任何帮助。谢谢,Norris



当我调试事件gvAccountStaff_RowDataBound时,数据列表显示SAPLeader字段。但是,当我触发事件时,下拉列表不是udpdating gvAccountStaff_RowUpdating,当它到达那里时,该值为null。其余的田地都很好。我不确定我想把这段代码放在哪里?控制ctrl2 = gvAccountStaff.FindControl(ddlType)作为DropDownList;

DropDownList ddl1 =(DropDownList)ctrl2;



我需要再次使用datalist绑定gridview?我不确定为什么它不起作用。提前感谢任何人,Norris








aspx code: <asp:TemplateField HeaderText="SAPLeader">

<asp:DropDownList runat="server" DataValueField="Catalog" DataTextField="Show" ID="ddlType" AutoPostBack="true" />
<%-- <asp:TextBox ID="txtSAPLeader" Text='<%#Eval("SAPLeader") %>'
runat="server" />--%>

The issue is when I display my datagridview gvAccountStaff, I have a column called SAPLeader which has a dropdownlist. When I select a name in the list it errors: Object reference not set to an instance of an object. The SAPLeader field is null. I tried replacing the @SAPLeader with the ddl1.SelectedValue that didn't worked neither. I would appreciate any help. Thanks, Norris

When I debug the event gvAccountStaff_RowDataBound, the datalist shows for the SAPLeader field. However, the dropdownlist is not udpdating when I fire event gvAccountStaff_RowUpdating the value is null by the time it gets there. The rest of the fields are fine. I not sure where I'm suppose to put this code? Control ctrl2 = gvAccountStaff.FindControl("ddlType") as DropDownList;
DropDownList ddl1 = (DropDownList)ctrl2;

Do I need to bind the gridview again with the datalist? I not sure why it doesn't work. Thanking anyone in advance, Norris



protected void gvAccountStaff_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            
            if (e.CommandName == "Add")
            {
               
                bool IsAdded = false;
                TextBox newLastName =
                (TextBox)gvAccountStaff.FooterRow.FindControl("newLastName");
                TextBox newFirstName = (TextBox)gvAccountStaff.FooterRow.FindControl("newFirstName");
                TextBox newBirthday = (TextBox)gvAccountStaff.FooterRow.FindControl("newBirthday");
                TextBox newNetID = (TextBox)gvAccountStaff.FooterRow.FindControl("newNetID");
                TextBox newPersonelNumber = (TextBox)gvAccountStaff.FooterRow.FindControl("newPersonelNumber");
                TextBox newEDSAnniversary = (TextBox)gvAccountStaff.FooterRow.FindControl("newEDSAnniversary");
                TextBox newPeopleManager = (TextBox)gvAccountStaff.FooterRow.FindControl("newPeopleManager");
                TextBox newSAPLeader = (TextBox)gvAccountStaff.FooterRow.FindControl("newSAPLeader");
                TextBox newHomeAddress = (TextBox)gvAccountStaff.FooterRow.FindControl("newHomeAddress");
                TextBox newHomeCity = (TextBox)gvAccountStaff.FooterRow.FindControl("newHomeCity");
                TextBox newHomeState = (TextBox)gvAccountStaff.FooterRow.FindControl("newHomeState");
                TextBox newHomeZip = (TextBox)gvAccountStaff.FooterRow.FindControl("newHomeZip");
                TextBox newWorkMailstop = (TextBox)gvAccountStaff.FooterRow.FindControl("newWorkMailstop");
                TextBox newWorkAddress = (TextBox)gvAccountStaff.FooterRow.FindControl("newWorkAddress");
                TextBox newWorkCity = (TextBox)gvAccountStaff.FooterRow.FindControl("newWorkCity");
                TextBox newWorkState = (TextBox)gvAccountStaff.FooterRow.FindControl("newWorkState");
                TextBox newWorkZip = (TextBox)gvAccountStaff.FooterRow.FindControl("newWorkZip");

                //   TextBox Grade = (TextBox)gvSubDetails.FooterRow.FindControl("newGrade");
                using (SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLStaffingConn"].ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        DropDownList ctrl2 = (DropDownList)gvAccountStaff.Rows[7].FindControl("dd1Type");
                        string selectedValue = ctrl2.SelectedItem.Value;
                        string selectedText = ctrl2.SelectedItem.Text;
                        //here i'd added "@" for continuous string in new line
                        cmd.CommandText = @"INSERT INTO CMS_DC_AccountStaff(LastName, FirstName, Birthday, NetID, PersonelNumber, EDSAnniversary,PeopleManager, SAPLeader, HomeAddress, HomeCity, HomeState, HomeZip, WorkAddress, WorkMailstop, WorkCity, WorkState, WorkZip)
                                   VALUES(@LastName,@FirstName,@Birthday,@NetID,@PersonelNumber,@EDSAnniversary,@PeopleManager,@ctrl2,@HomeAddress,@HomeCity,@HomeState,@HomeZip,@WorkAddress,@WorkMailstop,@WorkCity,@WorkState,@WorkZip)";

                        cmd.Parameters.AddWithValue("@LastName", newLastName.Text);
                        cmd.Parameters.AddWithValue("@FirstName", newFirstName.Text);
                        cmd.Parameters.AddWithValue("@Birthday", newBirthday.Text);
                        cmd.Parameters.AddWithValue("@NetID", newNetID.Text);
                        cmd.Parameters.AddWithValue("@PersonelNumber", newPersonelNumber.Text);
                        cmd.Parameters.AddWithValue("@EDSAnniversary", newEDSAnniversary.Text);
                        cmd.Parameters.AddWithValue("@PeopleManager", newPeopleManager.Text);
                        cmd.Parameters.AddWithValue("@ctrl2", ctrl2.Text);
                        cmd.Parameters.AddWithValue("@HomeAddress", newHomeAddress.Text);
                        cmd.Parameters.AddWithValue("@HomeCity", newHomeCity.Text);
                        cmd.Parameters.AddWithValue("@HomeState", newHomeState.Text);
                        cmd.Parameters.AddWithValue("@HomeZip", newHomeZip.Text);
                        cmd.Parameters.AddWithValue("@WorkAddress", newWorkAddress.Text);
                        cmd.Parameters.AddWithValue("@WorkMailstop", newWorkMailstop.Text);
                        cmd.Parameters.AddWithValue("@WorkCity", newWorkCity.Text);
                        cmd.Parameters.AddWithValue("@WorkState", newWorkState.Text);
                        cmd.Parameters.AddWithValue("@WorkZip", newWorkZip.Text);

                        cmd.Connection = sqlCon;
                        sqlCon.Open();
                        IsAdded = cmd.ExecuteNonQuery() > 0;
                        sqlCon.Close();
                    }
                }
                if (IsAdded)
                {
                    lblMsg.Text = "'" + newFirstName.Text + " " + newLastName.Text + "' Account Staff added successfully!";
                      lblMsg.ForeColor = System.Drawing.Color.Green;

                    BindSubjectData();
                }
                else
                {
                    lblMsg.Text = "Error while adding '" + newFirstName.Text + " " + newLastName.Text + "' subject details";
                      lblMsg.ForeColor = System.Drawing.Color.Red;
                }
            }
        }







我需要将ctrl2更改为其他内容以进行插入?




Do I need to change the ctrl2 to something else for insert?

推荐答案

嗨Norris,



我通过了代码你提供了。



如果SAPLeader在单击Edit时更改为下拉列表,为什么从 txtSAPLeader 获取值?你应该从下拉列表中得到它。

Hi Norris,

I went through the code you have provided.

If SAPLeader changes to drop down list on clicking Edit, why are you getting the value from txtSAPLeader? You should get it from the drop down list.
TextBox SAPLeader = (TextBox)gvAccountStaff.Rows[e.RowIndex].FindControl("txtSAPLeader");



有几个地方可能是您面临的问题的原因。


There are couple of places which might be the reason for the issue you are facing.

<asp:dropdownlist runat="server" datavaluefield="Catalog" datatextfield="Show" id="ddlType" autopostback="true" xmlns:asp="#unknown" />



你们每次用户更改下拉列表中的选择时,是否需要回传表单?如果未设置


Do you need the form to post-back every time the user changes the selection in the drop down list? If not set

AutoPostBack="false"



因为AutoPostBack将导致表单重新加载并重置下拉列表中的用户选择。 />
将行


Because AutoPostBack will cause the form to reload and reset the user selection in the drop down list.
Change the line

Control ctrl2 = gvAccountStaff.FindControl("ddlType") as DropDownList;



改为


to

DropDownList ctrl2 = (DropDownList)gvAccountStaff.Rows[e.RowIndex].FindControl("ddlType");



以上行确保你正在从正在编辑的行中获取下拉列表。

如果ctrl2不为null,你可以通过


Above line makes sure you are getting the drop down list from the row that is being edited.
If the ctrl2 is not null, you can get the selected value by

string selectedValue = ctrl2.SelectedItem.Value;

和选定的文字

and selected text by

string selectedText = ctrl2.SelectedItem.Text;



根据您的更新需要使用所选项目的值/文本。请尝试这些,看它是否有效。


Use the value/text of the selected item as per your need to update. Please try these and see if it works.


这篇关于从UpdateView中的GridView中的下拉列表中获取选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆