Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
I have the following database design:
 
    Employee Table: Username, Name, JobTitle, BadgeNo, IsActive, DivisionCode
    Divisions Table: SapCode, DivisionShortcut
***(DivisionCode is a foreign key to the SapCode in the Divisions Table)***
 
And I have a GridView that I am using it to add, delete and update/edit the employees information. This information is employee Username, Name, BadgeNo, JobTitle, IsActive and the DivisionShortcut. The Divisions will be listed in DropDownList. The problem now is: with updating the division of the employee. I wrote the code but still this column is not updated. I don't have any errors in the debugging. So how to get this column updated with the DropDownList inside the GridView?
 
ASP.NET code:
    <asp:GridView ID="GridView1" runat="server" AllowSorting="True" 
                AutoGenerateColumns="False" DataKeyNames="Username" 
                DataSourceID="SqlDataSource1" BorderWidth="1px" BackColor="#DEBA84" 
                 CellPadding="3" CellSpacing="2" BorderStyle="None" 
                 BorderColor="#DEBA84">
                <FooterStyle ForeColor="#8C4510" 
                  BackColor="#F7DFB5"></FooterStyle>
                <PagerStyle ForeColor="#8C4510" 
                  HorizontalAlign="Center"></PagerStyle>
                <HeaderStyle ForeColor="White" Font-Bold="True" 
                  BackColor="#A55129"></HeaderStyle>
                <Columns>
                    <asp:CommandField ButtonType="Image" ShowEditButton="true" ShowCancelButton="true"
                                    EditImageUrl="Images/icons/edit24.png" UpdateImageUrl="Images/icons/update24.png" 
                                    CancelImageUrl="Images/icons/cancel324.png" />
    
                    <asp:TemplateField HeaderText="Division">
                        <ItemTemplate>
                            <%# Eval("DivisionShortcut")%>
                            <asp:HiddenField ID="divisioncode" value='<%#Eval("divisioncode")%>' runat="server" />
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:DropDownList ID="DivisionsList" runat="server" DataSourceID="DivisionsListDataSource"
                                              DataTextField="DivisionShortcut" DataValueField="SapCode">
                            </asp:DropDownList>
                        </EditItemTemplate>
                    </asp:TemplateField>
    
                    <asp:BoundField DataField="Username" HeaderText="Network ID" ReadOnly="True" 
                        SortExpression="Username" />
                        
                    <asp:TemplateField HeaderText="Name">
                        <ItemTemplate>
                            <%# Eval("Name")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("Name")%>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
    
                    <asp:TemplateField HeaderText="Job Title">
                        <ItemTemplate>
                            <%# Eval("JobTitle")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtJobTitle" runat="server" Text='<%# Bind("JobTitle")%>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
    
                    <asp:TemplateField HeaderText="Badge No.">
                        <ItemTemplate>
                            <%# Eval("BadgeNo")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtBadgeNo" runat="server" Text='<%# Bind("BadgeNo")%>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
    
                    <asp:TemplateField HeaderText="Is Active?">
                        <ItemTemplate>
                            <%# Eval("IsActive")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:CheckBox ID="isActive" runat="server" 
                                          Checked='<%# Eval("IsActive").ToString().Equals("True") %>'/>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    
                    <asp:TemplateField HeaderText="Delete?">
                        <ItemTemplate>
                            <span  önclick="return confirm('Are you sure to Delete the record?')">
                                <asp:ImageButton ID="lnkB" runat="server" ImageUrl="Images/icons/delete24.png" CommandName="Delete" />
                            </span>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:UsersInfoDBConnectionString %>" 
                
                SelectCommand="SELECT     dbo.Divisions.DivisionShortcut,dbo.employee.DivisionCode, dbo.employee.Username, dbo.employee.Name, dbo.employee.JobTitle, dbo.employee.BadgeNo, dbo.employee.IsActive
                        FROM         dbo.Divisions INNER JOIN
                                    dbo.employee ON dbo.Divisions.SapCode = dbo.employee.DivisionCode"
                UpdateCommand="UPDATE [employee] SET [Name] = @Name, [JobTitle] = @JobTitle, 
                                                    [BadgeNo] = @BadgeNo WHERE [Username] = @Username"
                DeleteCommand="DELETE FROM [employee] WHERE [Username] = @Username">
                <UpdateParameters>
                    <asp:Parameter Name="Name" Type="String"  />
                    <asp:Parameter Name="JobTitle" Type="String" />
                    <asp:Parameter Name="BadgeNo" Type="String" />
                    <asp:Parameter Name="Username" Type="String" />
                </UpdateParameters>
                <DeleteParameters>
                    <asp:Parameter Name="Username" Type="String" />
                </DeleteParameters>
            </asp:SqlDataSource>
    
            <asp:SqlDataSource ID="DivisionsListDataSource" runat="server" 
                ConnectionString="<%$ ConnectionStrings:UsersInfoDBConnectionString %>" 
                SelectCommand="SELECT * FROM Divisions">
            </asp:SqlDataSource>
 

Code-Behind:
    //For editing any row in the GridView
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) 
        {
            GridView1.EditIndex = e.NewEditIndex;
        }
    
        //For canceling any editng in any row in the GridView
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            e.Cancel = true;
            GridView1.EditIndex = -1;
        }
    
        //For updating the information in any row in the GridView
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow gvrow = GridView1.Rows[e.RowIndex];
    
            DropDownList DivisionsList = (DropDownList)gvrow.FindControl("DivisionsList");
            HiddenField hidden = (HiddenField)gvrow.FindControl("divisioncode");
            string division_code = hidden.Value.ToString();
    
            TextBox txtEmployeeName = (TextBox)gvrow.FindControl("txtEmployeeName");
            TextBox txtJobTitle = (TextBox)gvrow.FindControl("txtJobTitle");
            TextBox txtBadgeNo = (TextBox)gvrow.FindControl("txtBadgeNo");
    
            CheckBox isActive = (CheckBox)gvrow.FindControl("isActive");
    
            //For getting the ID (primary key) of that row
            string username = GridView1.DataKeys[e.RowIndex].Value.ToString();
    
            string name = txtEmployeeName.Text;
            string jobTitle = txtJobTitle.Text;
            string badgeNo = txtBadgeNo.Text;
            string division = DivisionsList.SelectedValue.ToString();
    
            //string divisioncode = DivisionsList.SelectedValue;
    
            UpdateEmployeeInfo(username, name, jobTitle, badgeNo, division, division_code);
        }
    
    
        private void UpdateEmployeeInfo(string username, string name, string jobTitle, string badgeNo, string division, string divisioncode)
        {
            string connString = ConfigurationManager.ConnectionStrings["UsersInfoDBConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(connString);
            string update = @"UPDATE Employee SET Name = @Name, JobTitle = @JobTitle, 
                                BadgeNo = @BadgeNo WHERE Username = @Username; 
                                UPDATE Divisions SET [DivisionShortcut] = @division WHERE SapCode = @SapCode;";
    
            SqlCommand cmd = new SqlCommand(update, conn);
    
            cmd.Parameters.AddWithValue("@Name", name);
            cmd.Parameters.AddWithValue("@JobTitle", jobTitle);
            cmd.Parameters.AddWithValue("@BadgeNo", badgeNo);
            cmd.Parameters.AddWithValue("@division", division);
            cmd.Parameters.AddWithValue("@Username", username);
            cmd.Parameters.AddWithValue("@SapCode", divisioncode);
            //cmd.Parameters.AddWithValue("@IsActive", isActive.checked);
    
            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
    
                GridView1.EditIndex = -1;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cmd.Dispose();
                conn.Close();
                conn.Dispose();
            }
            GridView1.DataBind();
        }
 
UPDATE:
 
The complete updated code:
ASP.NET Code:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" 
            AutoGenerateColumns="False" DataKeyNames="Username" 
            DataSourceID="SqlDataSource1" BorderWidth="1px" BackColor="#DEBA84" 
             CellPadding="3" CellSpacing="2" BorderStyle="None" 
             BorderColor="#DEBA84">
            <FooterStyle ForeColor="#8C4510" 
              BackColor="#F7DFB5"></FooterStyle>
            <PagerStyle ForeColor="#8C4510" 
              HorizontalAlign="Center"></PagerStyle>
            <HeaderStyle ForeColor="White" Font-Bold="True" 
              BackColor="#A55129"></HeaderStyle>
            <Columns>
                <asp:CommandField ButtonType="Image" ShowEditButton="true" ShowCancelButton="true"
                                EditImageUrl="Images/icons/edit24.png" UpdateImageUrl="Images/icons/update24.png" 
                                CancelImageUrl="Images/icons/cancel324.png" />
 
                <asp:TemplateField HeaderText="Division">
                    <ItemTemplate>
                        <%# Eval("DivisionShortcut")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="DivisionsList" runat="server" DataSourceID="DivisionsListDataSource"
                                          DataTextField="DivisionShortcut" DataValueField="SapCode">
                        </asp:DropDownList>
                    </EditItemTemplate>
                </asp:TemplateField>
 
                <asp:BoundField DataField="Username" HeaderText="Network ID" ReadOnly="True" 
                    SortExpression="Username" />
                    
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <%# Eval("Name")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("Name")%>' />
                    </EditItemTemplate>
                </asp:TemplateField>
 
                <asp:TemplateField HeaderText="Job Title">
                    <ItemTemplate>
                        <%# Eval("JobTitle")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtJobTitle" runat="server" Text='<%# Bind("JobTitle")%>' />
                    </EditItemTemplate>
                </asp:TemplateField>
 
                <asp:TemplateField HeaderText="Badge No.">
                    <ItemTemplate>
                        <%# Eval("BadgeNo")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtBadgeNo" runat="server" Text='<%# Bind("BadgeNo")%>' />
                    </EditItemTemplate>
                </asp:TemplateField>
 
                <asp:TemplateField HeaderText="Is Active?">
                    <ItemTemplate>
                        <%# Eval("IsActive")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:CheckBox ID="isActive" runat="server" 
                                      Checked='<%# Eval("IsActive").ToString().Equals("True") %>'/>
                    </EditItemTemplate>
                </asp:TemplateField>
                
                <asp:TemplateField HeaderText="Delete?">
                    <ItemTemplate>
                        <span  önclick="return confirm('Are you sure to Delete the record?')">
                            <asp:ImageButton ID="lnkB" runat="server" ImageUrl="Images/icons/delete24.png" CommandName="Delete" />
                        </span>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:UsersInfoDBConnectionString %>" 
            
            SelectCommand="SELECT     dbo.Divisions.DivisionShortcut,dbo.employee.DivisionCode, dbo.employee.Username, dbo.employee.Name, dbo.employee.JobTitle, dbo.employee.BadgeNo, dbo.employee.IsActive
                    FROM         dbo.Divisions INNER JOIN
                                dbo.employee ON dbo.Divisions.SapCode = dbo.employee.DivisionCode"
            UpdateCommand="UPDATE [employee] SET [Name] = @Name, [JobTitle] = @JobTitle, [DivisionCode] = @DivisionCode, 
                                                [BadgeNo] = @BadgeNo WHERE [Username] = @Username"
            DeleteCommand="DELETE FROM [employee] WHERE [Username] = @Username">
            <UpdateParameters>
                <asp:Parameter Name="Name" Type="String"  />
                <asp:Parameter Name="JobTitle" Type="String" />
                <asp:Parameter Name="BadgeNo" Type="String" />
                <asp:Parameter Name="Username" Type="String" />
<asp:Parameter Name="DivisionCode" Type="String" />
            </UpdateParameters>
            <DeleteParameters>
                <asp:Parameter Name="Username" Type="String" />
            </DeleteParameters>
        </asp:SqlDataSource>
 
        <asp:SqlDataSource ID="DivisionsListDataSource" runat="server" 
            ConnectionString="<%$ ConnectionStrings:UsersInfoDBConnectionString %>" 
            SelectCommand="SELECT * FROM Divisions"
            InsertCommand="INSERT INTO [Divisions] ([SapCode], [DivisionShortcut]) VALUES (@SapCode, @DivisionShortcut)"
            UpdateCommand="UPDATE [Divisions] SET [DivisionShortcut] = @DivisionShortcut WHERE [SapCode] = @SapCode">
            <DeleteParameters>
                <asp:Parameter Name="SapCode" Type="Double" />
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="SapCode" Type="Double" />
                <asp:Parameter Name="DivisionShortcut" Type="String" />
            </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="DivisionShortcut" Type="String" />
                <asp:Parameter Name="SapCode" Type="Double" />
            </UpdateParameters>
        </asp:SqlDataSource>
 
Code-Behind:
//For updating the information in any row in the GridView
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow gvrow = GridView1.Rows[e.RowIndex];
 
        DropDownList DivisionsList = (DropDownList)gvrow.FindControl("DivisionsList");
 
        TextBox txtEmployeeName = (TextBox)gvrow.FindControl("txtEmployeeName");
        TextBox txtJobTitle = (TextBox)gvrow.FindControl("txtJobTitle");
        TextBox txtBadgeNo = (TextBox)gvrow.FindControl("txtBadgeNo");
 
        CheckBox isActive = (CheckBox)gvrow.FindControl("isActive");
 
        //For getting the ID (primary key) of that row
        string username = GridView1.DataKeys[e.RowIndex].Value.ToString();
 
        string name = txtEmployeeName.Text;
        string jobTitle = txtJobTitle.Text;
        string badgeNo = txtBadgeNo.Text;
        string division_code = DivisionsList.SelectedValue.ToString();
 
        UpdateEmployeeInfo(username, name, jobTitle, badgeNo, division_code);
    }
 

    private void UpdateEmployeeInfo(string username, string name, string jobTitle, string badgeNo, string division_code)
    {
        string connString = ConfigurationManager.ConnectionStrings["UsersInfoDBConnectionString"].ConnectionString;
        SqlConnection conn = new SqlConnection(connString);
        string update = @"UPDATE Employee SET Name = @Name, JobTitle = @JobTitle, BadgeNo = @BadgeNo, DivisionCode = @DivisionCode
                                            WHERE Username = @Username;";
 
        SqlCommand cmd = new SqlCommand(update, conn);
 
        cmd.Parameters.AddWithValue("@Username", username);
        cmd.Parameters.AddWithValue("@Name", name);
        cmd.Parameters.AddWithValue("@JobTitle", jobTitle);
        cmd.Parameters.AddWithValue("@BadgeNo", badgeNo);
        cmd.Parameters.AddWithValue("@DivisionCode", division_code);
        //cmd.Parameters.AddWithValue("@IsActive", isActive.checked);

        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
 
            GridView1.EditIndex = -1;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            cmd.Dispose();
            conn.Close();
            conn.Dispose();
        }
        GridView1.DataBind();
    }
 
Now, I am getting this following error and I don't know why since the column will be as a dropdownlist in the Edit mode which means there is a data and there is nothing called NULL:
Cannot insert the value NULL into column 'DivisionCode', table 'UsersInfoDB.dbo.employee'; column does not allow nulls. UPDATE fails.
The statement has been terminated.


So how to fix this error?
Posted 13-Jul-12 22:58pm
Edited 14-Jul-12 1:41am
v3

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

***(DivisionCode is a foreign key to the SapCode in the Divisions Table)***
Let me explain you concept of Foreign keys a little. If a column is a foreign key then that field can be updated by an update statement on that table as long as the value is valid and already exists in actual table from where the key was referenced.
 
Example:
TableA
AID Name
1  ABC
2  XYZ
 
TableB (has tableA ID as foreign Key)
BID Class AID
1   QW    2
2   SD    1
3   MM    3 : WRONG! Since this is a FK, value must be valid and already present in Table A
 

Now, to update employee all you need to do is to update Employee table and not touch Division table at all. I see you are trying to update that too. Wrong. Remove the update code for that.
 
Further, couple of things:
1. Your UPDATE query in SQLDatasource1 does not have any update for Division Code. Update it to:
UpdateCommand="UPDATE [employee] SET [Name] = @Name, [JobTitle] = @JobTitle, [DivisionCode] = @DivisionCode, [BadgeNo] = @BadgeNo WHERE [Username] = @Username"
2. Following code to pick and pass the new selected divisioncode for employee is wrong.
HiddenField hidden = (HiddenField)gvrow.FindControl("divisioncode");
string division_code = hidden.Value.ToString();
string division = DivisionsList.SelectedValue.ToString();
Hidden field has previously selected value and will pass on as is not updating the new data. This field is not required at all. Remove hidden field and related code.
Further, dropdownlist selected value is what you want to pass for division code. (Selected text will be text and value will be the ID which is needed.)
Change the code to:
string division_code = DivisionsList.SelectedValue.ToString();
Later, modify the update code and query to:
string update = @"UPDATE Employee SET Name = @Name, JobTitle = @JobTitle, BadgeNo = @BadgeNo, DivisionCode = @DivisionCode
WHERE Username = @Username;";
cmd.Parameters.AddWithValue("@DivisionCode", division_code);
 
That's it! 
  Permalink  
Comments
matrix388 at 14-Jul-12 7:35am
   
Thanks very much for your help and explanation. I updated my code according to your help but it is still not working and I am getting this error:

Cannot insert the value NULL into column 'DivisionCode', table 'UsersInfoDB.dbo.employee'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
 
and I don't know why. Could you please have a look at my updated code?
matrix388 at 14-Jul-12 7:49am
   
Thanks for your help. I got the answer now. I really appreciate your help man.
Sandeep Mewara at 14-Jul-12 11:57am
   
Welcome.

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 6,725
1 OriginalGriff 6,696
2 CPallini 5,315
3 George Jonsson 3,589
4 Gihan Liyanage 2,650


Advertise | Privacy | Mobile
Web04 | 2.8.140921.1 | Last Updated 14 Jul 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100