Click here to Skip to main content
16,004,927 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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.


C#
  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 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



C#
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;
                }
            }
        }



Do I need to change the ctrl2 to something else for insert?
Posted
Updated 19-May-15 17:11pm
v4
Comments
Sergey Alexandrovich Kryukov 18-May-15 19:09pm    
GridView? Which one? Full type name, please.
—SA
Norris Chappell 18-May-15 19:28pm    
Sorry don't know what you mean "Full Type name"? here is my aspx code: <asp:TemplateField HeaderText="SAPLeader">
<edititemtemplate>
<asp:DropDownList runat="server" DataValueField="Catalog" DataTextField="Show" ID="ddlType" AutoPostBack="true" />
<%-- <asp:TextBox ID="txtSAPLeader" Text='<%#Eval("SAPLeader") %>'
runat="server" />--%>

<itemtemplate>
<asp:Label ID="lblSAPLeader" Text='<%#Eval("SAPLeader") %>'
runat="server" />

<footertemplate>
<asp:DropDownList runat="server" DataValueField="Catalog" DataTextField="Show" ID="ddlType" AutoPostBack="true" />
Sergey Alexandrovich Kryukov 18-May-15 19:44pm    
The answer would be: "System.Web.UI.WebControls.GridView", but if need to add code (good idea), please move it to the question, with appropriate explanations of the problem, to the question, using "Improve question".
—SA
Norris Chappell 18-May-15 22:42pm    
Hi Sergey, I updated my question. Were you able to take a look at it? Is it something to the way that page is being bound? With debug, I was able to see my dropdownlist but when I go to update I am losing it somehow. Thanks, Norris
Sergey Alexandrovich Kryukov 18-May-15 23:17pm    
First, thank you for improving the question, it should help...
—SA

1 solution

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"

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");

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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900