skip to Main Content

There are 2 parts to my question. Please bear with me… just learning this stuff.

I have a GridView that allows editing, which will update a database table. Issue #1 is that I cannot seem to get the values from the GridView in my code behind. I keep getting an error. I’ve tried it several different ways and I’m at a total roadblock.

Here is the ASP.NET markup:

<asp:GridView ID="ItemView" runat="server" 
     AutoGenerateColumns="false" AllowPaging="true" 
     HorizontalAlign="Center"
     PageSize="10" HeaderStyle-BackColor="#6f263d" 
     HeaderStyle-ForeColor="White" CellPadding="7" CellSpacing="0" 
     DataKeyNames="orderItemId" AllowSorting="True" 
     AlternatingRowStyle-BorderStyle="Solid" AlternatingRowStyle-BackColor="White" 
     AlternatingRowStyle-ForeColor="#6f263d"  AlternatingRowStyle-CssClass="fancylink" 
     Font-Size="Small" RowStyle-BackColor="#63666A" 
     RowStyle-BorderStyle="None" RowStyle-ForeColor="White" 
     SelectedRowStyle-BackColor="#D3D0C8" SelectedRowStyle-ForeColor="Black" 
     Width="100%" 
     OnSelectedIndexChanged="ItemView_SelectedIndexChanged" 
     ShowHeaderWhenEmpty="false" PagerStyle-CssClass="fancylink" 
     PagerStyle-BackColor="#6f263d" PagerStyle-ForeColor="White" 
     PagerSettings-FirstPageText="First Page&nbsp;&nbsp;&nbsp;"  
     PagerSettings-Mode="NextPrevious" PagerSettings-NextPageText="Next Page" 
     PagerSettings-LastPageText="End" PagerSettings-PreviousPageText="Previous Page" 
     PagerStyle-HorizontalAlign="Center" PagerStyle-Width="20%" 
     OnPageIndexChanging="OnPageIndexChanging" 
     OnRowDataBound="ItemView_RowDataBound" 
     OnRowEditing="ItemView_EditRow" 
     OnRowUpdating ="ItemView_OnRowUpdating" 
     BorderStyle="None" 
     OnRowCancelingEdit ="ItemView_RowCancelingEdit" 
     OnRowDeleting="ItemView_DeleteRow" 
     OnSelectedIndexChanging="ItemView_OnSelectedIndexChanging" 
     AutoGenerateSelectButton="False">
    <Columns>
        <asp:TemplateField HeaderText="ID">
            <ItemTemplate>
                <asp:Label ID="lbl_itemId" runat="server" Text='<%#Eval("orderItemId") %>' ReadOnly="True"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Item Description">
            <ItemTemplate>
                <div style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 400px;">
                    <asp:LinkButton ID="btn_Select" runat="server" Text='<%#Eval("item") %>' ToolTip='<%# Eval("item") %>' CommandName="Select" ItemStyle-HorizontalAlign="Center" />
                </div>
            </ItemTemplate>
        </asp:TemplateField>                        
        <asp:TemplateField HeaderText="PO Num">
            <ItemTemplate>
                <asp:Label ID="lbl_poNum" runat="server" Text='<%#Eval("poNum") %>' NullDisplayText="--"></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txt_poNum" runat="server" Text='<%#Eval("poNum") %>' Width="75px"></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Item Amount">
            <ItemTemplate>
                <asp:Label ID="lbl_amount" runat="server" Text='<%#Eval("amount") %>' NullDisplayText="--"></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txt_amount" runat="server" Text='<%#Eval("amount") %>' Width="60px"></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Quantity">
            <ItemTemplate>
                <asp:Label ID="lbl_quantity" runat="server" Text='<%#Eval("quantity") %>' NullDisplayText="--" ReadOnly="True"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Date Ordered">
            <ItemTemplate>
                <asp:Label ID="lbl_ordered" runat="server" Text='<%#Eval("ordered") %>' NullDisplayText="--"></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txt_ordered" runat="server" Text='<%#Eval("ordered") %>' Width="75px"></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Date Received">
            <ItemTemplate>
                <asp:Label ID="lbl_received" runat="server" Text='<%#Eval("received") %>' NullDisplayText="--"></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txt_received" runat="server" Text='<%#Eval("received") %>' Width="75px"></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Tech Notes">
            <ItemTemplate>
                <div style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 500px;">
                    <asp:Label ID="lbl_techNotes" runat="server" Text='<%#Eval("techNotes") %>' ToolTip='<%# Eval("techNotes") %>' NullDisplayText="--"></asp:Label>
                </div>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txt_techNotes" runat="server" Text='<%#Eval("techNotes") %>' Width="380px"></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="btn_Edit" runat="server" Text="Edit" CommandName="Edit" ItemStyle-HorizontalAlign="Center"/>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:LinkButton ID="btn_Update" runat="server" Text="Update" CommandName="Update" ItemStyle-HorizontalAlign="Center" />
                <asp:LinkButton ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel" ItemStyle-HorizontalAlign="Center" />
            </EditItemTemplate>
        </asp:TemplateField>
   </Columns>
</asp:GridView>

And in my code behind:

    protected void ItemView_OnRowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = ItemView.SelectedRow;
        int itemNum = Convert.ToInt16(ItemView.DataKeys[e.RowIndex].Values[0]);

        string poNum = ((System.Web.UI.WebControls.TextBox)row.FindControl("txt_poNum")).Text;
        string amount = ((System.Web.UI.WebControls.TextBox)row.FindControl("txt_amount")).Text;
        string quantity = ((System.Web.UI.WebControls.TextBox)row.FindControl("txt_quantity")).Text;
        string ordered = ((System.Web.UI.WebControls.TextBox)row.FindControl("txt_ordered")).Text;
        string received = ((System.Web.UI.WebControls.TextBox)row.FindControl("txt_received")).Text;
        string techNotes = ((System.Web.UI.WebControls.TextBox)row.FindControl("txt_techNotes")).Text;


        string updateQuery = "UPDATE OrderItems SET ";
        bool firstField = true;

        if (!string.IsNullOrEmpty(poNum))
        {
            updateQuery += "purchaseOrderNum = @OrderNum";
            firstField = false;
        }

        if (!string.IsNullOrEmpty(amount))
        {
            if (!firstField) updateQuery += ", ";
            updateQuery += "itemAmt = @Amount";
            firstField = false;
        }

        if (!string.IsNullOrEmpty(quantity))
        {
            if (!firstField) updateQuery += ", ";
            updateQuery += "quantity = @Quantity";
            firstField = false;
        }

        if (!string.IsNullOrEmpty(ordered))
        {
            if (!firstField) updateQuery += ", ";
            updateQuery += "dateOrdered = @Ordered";
            firstField = false;
        }

        if (!string.IsNullOrEmpty(received))
        {
            if (!firstField) updateQuery += ", ";
            updateQuery += "dateReceived = @Received";
            firstField = false;
        }

        if (!string.IsNullOrEmpty(techNotes))
        {
            if (!firstField) updateQuery += ", ";
            updateQuery += "techNotes = @TechNotes";
        }

        updateQuery += "WHERE orderItemId = @ID";

        using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ForCustomWebApps"]))
        {
            using (SqlCommand cmd = new SqlCommand(updateQuery, conn))
            {
                cmd.Parameters.AddWithValue("@ID", id);

                if (!string.IsNullOrEmpty(poNum)) 
                     cmd.Parameters.AddWithValue("@OrderNum", poNum);

                if (!string.IsNullOrEmpty(amount)) 
                     cmd.Parameters.AddWithValue("@Amount", amount);

                if (!string.IsNullOrEmpty(quantity)) 
                     cmd.Parameters.AddWithValue("@Quantity", quantity);

                if (!string.IsNullOrEmpty(ordered)) 
                     cmd.Parameters.AddWithValue("@Ordered", ordered);

                if (!string.IsNullOrEmpty(received)) 
                     cmd.Parameters.AddWithValue("@Received", received);

                if (!string.IsNullOrEmpty(techNotes)) 
                     cmd.Parameters.AddWithValue("@TechNotes", techNotes);

                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
            }
        }

        ItemView.EditIndex = -1;
        BindGrid();
    }

I have confirmed that the first 2 lines are indeed getting me the correct row (itemNum):

GridViewRow row = ItemView.SelectedRow;
int itemNum = Convert.ToInt16(ItemView.DataKeys[e.RowIndex].Values[0]);

But then it just breaks. When I run it I get:

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 116: int itemNum = Convert.ToInt16(ItemView.DataKeys[e.RowIndex].Values[0]);
Line 117:
Line 118: string poNum = ((System.Web.UI.WebControls.TextBox)row.FindControl("txt_poNum")).Text;

So that’s the first problem.

The second issue is that someone can edit multiple fills in the gridview row, but they don’t HAVE to edit them all. They might enter a PONumber and an amount, but no techNotes or Received Date. I need an elegant way to check for empty fields for building my update statement. You can see what I’ve done, which is modeled off something I found on the web. Is there a better way I can do this a loop?

Thank you in advance for any help you can give me. I’m pulling my hair out!

2

Answers


  1. The following shows one of the ways one can use a GridView in an ASP.NET Web Application (.NET Framework) project to display and update data.

    Try the following:

    VS 2022:

    Create a new ASP.NET Web Application (.NET Framework)

    • Open Visual Studio 2022
    • Click Create a new project

    CreateNewProject

    • For filter, select

    Filter

    • Select ASP.NET Web Application (.NET Framework)

      ASP.NETWebTemplate

    • Click Next

    • Enter desired project name (ex: GridViewTestA)

    • Select desired framework (ex: .NET Framework 4.8)

    • Click Create

    • On the "Create a new ASP.NET Web Application" form, select Empty.

      Empty

      If you’re using "http" instead of "https", under "Advance", uncheck "Configure for HTTPS".

      Advanced

    • Click Create


    Add Web Form to project

    • In VS menu, click Project
    • Select Add New Item…
    • On left side, expand "Web". Select Web Form (name: default.aspx)
    • Click Add

    Open Solution Explorer

    • In VS menu, click View
    • Select Solution Explorer

    default.aspx:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" EnableSessionState="true"  Inherits="GridViewTestA._default" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head runat="server">
            <title>Order Items</title>
        </head>
        <body>
            <form id="form1" runat="server">
                 
                <div style="position:absolute;left:50px; top:100px">
                    <asp:GridView ID="GridViewItem" runat="server" 
                        AllowPaging="true" AllowSorting="True" 
                        AlternatingRowStyle-BorderStyle="Solid" AlternatingRowStyle-BackColor="White" 
                        AlternatingRowStyle-ForeColor="#6f263d"  AlternatingRowStyle-CssClass="fancylink" 
                        AutoGenerateColumns="false" 
                        AutoGenerateSelectButton="False"
                        BorderStyle="None" 
                        CellPadding="7" CellSpacing="0" 
                        ConflictDetection="true"
                        DataKeyNames="Id"
                        Font-Size="Small" RowStyle-BackColor="#63666A" 
                        HeaderStyle-BackColor="#6f263d" 
                        HeaderStyle-ForeColor="White" 
                        HorizontalAlign="Center" 
                        OnPageIndexChanging="GridViewItem_PageIndexChanging"
                        OnRowCancelingEdit="GridViewItem_RowCancelingEdit"
                        OnRowCommand ="GridViewItem_RowCommand"
                        OnRowEditing="GridViewItem_RowEditing"
                        OnRowDataBound="GridViewItem_RowDataBound"
                        OnRowDeleting="GridViewItem_RowDeleting"
                        OnRowUpdating="GridViewItem_RowUpdating"
                        OnRowUpdated="GridViewItem_RowUpdated"
                        PageSize="10" 
                        PagerStyle-BackColor="#6f263d" PagerStyle-CssClass="fancylink" PagerStyle-ForeColor="White" 
                        PagerSettings-FirstPageText="First Page&nbsp;&nbsp;&nbsp;"  
                        PagerSettings-Mode="NextPrevious" PagerSettings-NextPageText="Next Page" 
                        PagerSettings-LastPageText="End" PagerSettings-PreviousPageText="Previous Page" 
                        PagerStyle-HorizontalAlign="Center" PagerStyle-Width="20%" 
                        RowStyle-BorderStyle="None" RowStyle-ForeColor="White" 
                        SelectedRowStyle-BackColor="#D3D0C8" SelectedRowStyle-ForeColor="Black" 
                        ShowHeaderWhenEmpty="false" >
                        
                        <Columns>
                            <%-- Id --%>
                            <asp:TemplateField HeaderText="ID">
                                <ItemTemplate>
                                    <asp:Label ID="lblId" runat="server" Text='<%# Bind("Id") %>' ReadOnly="True"></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            
                            <%-- Description --%>
                            <asp:TemplateField HeaderText="Item Description" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
                                    <div style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 400px;">
                                        <asp:LinkButton ID="btnSelect" runat="server" Text='<%# Bind("Description") %>' Tooltip='<%# Bind("Description") %>' CommandName="Select" CommandArgument='<%# Bind("ItemDetailId") %>' OnCommand="btnSelect_Command" ItemStyle-HorizontalAlign="Center" />
                                    </div>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:textbox ID="textBoxDescription" Text='<%# Bind("Description") %>' runat="server" ReadOnly="true" />
                                </EditItemTemplate>
                            </asp:TemplateField>     
    
                            <%-- PONum --%>
                            <asp:TemplateField HeaderText="PONum" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
                                    <asp:Label ID="lblPONum" runat="server" Text='<%# Bind("PONum") %>'  ControlStyle-Width ="30" ControlStyle-Height="40" ItemStyle-HorizontalAlign="Center" />
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:textbox ID="textBoxPONum" Text='<%# Bind("PONum") %>' runat="server" />
                                </EditItemTemplate>
                            </asp:TemplateField>
    
                            <%-- Amount --%>
                            <asp:TemplateField HeaderText="Amount" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
                                    <asp:Label ID="lblAmount" runat="server" Text='<%# Bind("Amount") %>'  ControlStyle-Width ="30" ControlStyle-Height="40" ItemStyle-HorizontalAlign="Center" />
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:textbox ID="textBoxAmount" Text='<%# Bind("Amount") %>' runat="server" />
                                </EditItemTemplate>
                            </asp:TemplateField>
    
                            <%-- Quantity --%>
                            <asp:TemplateField HeaderText="Quantity" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
                                    <asp:Label ID="lblQuantity" runat="server" Text='<%# Bind("Quantity") %>'  ControlStyle-Width ="30" ControlStyle-Height="40" ItemStyle-HorizontalAlign="Center" />
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:textbox ID="textBoxQuantity" Text='<%# Bind("Quantity") %>' runat="server" />
                                </EditItemTemplate>
                            </asp:TemplateField>
    
                            <%-- OrderedOn --%>
                            <asp:TemplateField HeaderText="OrderedOn" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
                                    <asp:Label ID="lblOrderedOn" runat="server" Text='<%# Bind("OrderedOn") %>'  ControlStyle-Width ="75" ControlStyle-Height="40" ItemStyle-HorizontalAlign="Center" />
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:textbox ID="textBoxOrderedOn"  Text='<%# Bind("OrderedOn") %>' TextMode="DateTime" runat="server" />
                                </EditItemTemplate>
                            </asp:TemplateField>
    
                            <%-- ReceivedOn --%>
                            <asp:TemplateField HeaderText="ReceivedOn" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
                                    <asp:Label ID="lblReceivedOn" runat="server" Text='<%# Bind("ReceivedOn") %>'  ControlStyle-Width ="75" ControlStyle-Height="40" ItemStyle-HorizontalAlign="Center" />
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:textbox ID="textBoxReceivedOn"  Text='<%# Bind("ReceivedOn") %>' TextMode="DateTime" runat="server" />
                                </EditItemTemplate>
                            </asp:TemplateField>
    
                            <%-- TechNotes --%>
                            <asp:TemplateField HeaderText="TechNotes" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
                                    <asp:Label ID="lblTechNotes" runat="server" Text='<%# Bind("TechNotes") %>'  ControlStyle-Width ="30" ControlStyle-Height="40" ItemStyle-HorizontalAlign="Center" />
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:textbox ID="textBoxTechNotes" Text='<%# Bind("TechNotes") %>' runat="server" />
                                </EditItemTemplate>
                            </asp:TemplateField>
    
                            <%-- ItemDetailId --%>
                            <asp:TemplateField HeaderText="ItemDetailId" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
                                    <asp:Label ID="lblItemDetailId" runat="server" Text='<%# Bind("ItemDetailId") %>'  ControlStyle-Width ="30" ControlStyle-Height="40" ItemStyle-HorizontalAlign="Center" />
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:textbox ID="textBoxItemDetailId" ReadOnly="true" Text='<%# Bind("ItemDetailId") %>' runat="server" />
                                </EditItemTemplate>
                            </asp:TemplateField>
    
                            <%-- Edit, Update, Cancel --%>
                            <asp:TemplateField HeaderText="" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
                                    <asp:LinkButton ID="btnEdit" runat="server" Text='Edit' ControlStyle-Width ="40" ControlStyle-Height="40" CommandName="Edit" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' OnCommand="btnEdit_Command" />
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:LinkButton ID="btnUpdate" runat="server" Text="Update" CommandName="Update" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' OnCommand="btnUpdate_Command" ItemStyle-HorizontalAlign="Center" />
                                    <asp:LinkButton ID="btnCancel" runat="server" Text="Cancel" CommandName="Cancel" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' OnCommand="btnCancel_Command" ItemStyle-HorizontalAlign="Center" />
                                
                                </EditItemTemplate>
                            </asp:TemplateField> 
    
                        </Columns>
                    </asp:GridView>
                </div>
    
            </form>
        </body>
    </html>
    

    Default.aspx.cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Data;
    using System.Diagnostics;
    using System.Reflection;
    using Microsoft.SqlServer.Server;
    using System.Security.Cryptography;
    using System.IO;
    
    namespace GridViewTestA
    {
        public partial class _default : System.Web.UI.Page
        {
            private DataTable _dt = new DataTable();
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!this.IsPostBack)
                {
                    LogMsg("!this.IsPostBack");
    
                    int rowsAffected = OrderItemsGetAndBindData();
                    LogMsg($"    rowsAffected: {rowsAffected}");
                }
                else
                {
                    LogMsg($"IsPostBack");
                }
            }
    
            private void LogMsg(string msg, bool includeTimeStamp = true)
            {
                if (includeTimeStamp)
                    msg = $"{DateTime.Now.ToString("HH:mm:ss.fff")} - {msg}";
    
                //ToDo: add desired code
                Debug.WriteLine(msg);
            }
    
            protected void btnEdit_Command(object sender, CommandEventArgs e)
            {
                LogMsg($"btnEdit_Command CommandName: '{e.CommandName}' CommandArgument: '{e.CommandArgument}'");
            }
    
            protected void btnSelect_Command(object sender, CommandEventArgs e)
            {
                LogMsg($"btnSelect_Command CommandName: '{e.CommandName}' CommandArgument: '{e.CommandArgument}'");
    
                //option 1 - pass 'Id' as a GET parameter
                string url = $"~/detail.aspx?Id={e.CommandArgument}";
                Response.Redirect(url, false);
    
                //option 2 - create session variable
                //Session["Id"] = e.CommandArgument;
    
                //string url = $"~/detail.aspx";
                //Response.Redirect(url);
            }
    
            protected void btnUpdate_Command(object sender, CommandEventArgs e)
            {
                LogMsg($"btnUpdate_Command CommandName: '{e.CommandName}' CommandArgument: '{e.CommandArgument}");
    
                /*
                //create reference
                LinkButton linkButton = (LinkButton)sender;
    
                //for 'Update', one can update the data here or in 'GridViewItem_RowCommand',
                //one would use the same code, except for the code to retrieve 'rowIndex'
                
                //option 1 - get row index
                int rowIndex = ((GridViewRow)(linkButton.NamingContainer)).RowIndex;
    
                //option 2 - get row index
                //int rowIndex = 0;
                //if (!Int32.TryParse(e.CommandArgument?.ToString(), out rowIndex))
                //    throw new InvalidDataException($"Couldn't parse CommandArgument ('{e.CommandArgument}').");
                
                //                           ...
                */
                
            }
    
            protected void btnCancel_Command(object sender, CommandEventArgs e)
            {
                LogMsg($"btnCancel_Command CommandName: '{e.CommandName}' CommandArgument: '{e.CommandArgument}'");
    
            }
    
            protected void GridViewItem_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
                LogMsg($"GridViewItem_RowCancelingEdit e.RowIndex: '{e.RowIndex}'");
                GridView gv = (GridView)sender;
                gv.EditIndex = -1;
                gv.DataBind();
            }
    
            protected void GridViewItem_PageIndexChanging(object sender, GridViewPageEventArgs e)
            {
                LogMsg($"GridViewItem_PageIndexChanging e.NewPageIndex: '{e.NewPageIndex}'");
            }
    
            protected void GridViewItem_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                GridView gv = (GridView)sender;
    
                LogMsg($"GridViewItem_RowCommand CommandName: '{e.CommandName}' CommandArgument: '{e.CommandArgument}'");
    
                if (e.CommandName == "Cancel")
                {
                    gv.EditIndex = -1;
                    OrderItemsGetAndBindData();
                }
                else if (e.CommandName == "Edit")
                {
                    int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
                    GridViewItem.EditIndex = rowIndex;
                    OrderItemsGetAndBindData();
                }
                else if (e.CommandName == "Update")
                {
                    //for 'Update', either use the code below or the code in 'btnUpdate_Command'.
                    //the code is identical, except for the code to retrieve 'rowIndex'
     
                    //option 1 - get row index
                    int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
    
                    //option 2 - get row index
                    //int rowIndex = 0;
                    //if (!Int32.TryParse(e.CommandArgument?.ToString(), out rowIndex))
                    //    throw new InvalidDataException($"Couldn't parse CommandArgument ('{e.CommandArgument}').");
    
                    //set value
                    GridViewItem.EditIndex = rowIndex;
    
                    //---------------------------------------
                    //for debugging
                    //---------------------------------------
                    for (int i = 0; i < GridViewItem.Rows[rowIndex].Controls.Count; i++)
                    {
                        //LogMsg($"[{i}]: {GridViewItem.Rows[rowIndex].Controls[i].ID} Type: {GridViewItem.Rows[rowIndex].Controls[i].GetType()?.ToString()}");
    
                        DataControlFieldCell cell = (DataControlFieldCell)GridViewItem.Rows[rowIndex].Controls[i];
    
                        for (int j = 0; j < cell.Controls.Count; j++)
                        {
                            //LogMsg($"    {cell.Controls[j].GetType()}");
    
                            if (cell.Controls[j].GetType() == typeof(Label))
                            {
                                //create reference
                                Label lbl = (Label)cell.Controls[j];
                                LogMsg($"    ID: '{lbl.ID}' Text: '{lbl.Text}'");
                            }
                            else if (cell.Controls[j].GetType() == typeof(TextBox))
                            {
                                //create reference
                                TextBox tb = (TextBox)cell.Controls[j];
                                LogMsg($"    ID: '{tb.ID}' Text: '{tb.Text}'");
                            }
                        }
                    }
                    //---------------------------------------
    
                    //option 1 - get 'Id'
                    int id = Convert.ToInt32(GridViewItem.DataKeys[rowIndex].Value?.ToString());
    
                    //option 2 - get 'Id'
                    //string idStr = ((Label)GridViewItem.Rows[rowIndex].FindControl("lblId")).Text;
                    //int id = 0;
                    //if (!Int32.TryParse(idStr, out id))
                    //    throw new InvalidDataException($"Error: Couldn't parse Id ('{idStr}')");
    
    
                    string description = ((TextBox)GridViewItem.Rows[rowIndex].FindControl("textBoxDescription")).Text;
                    LogMsg($"    description: '{description}'");
    
                    //PONum
                    string poNumStr = ((TextBox)GridViewItem.Rows[rowIndex].FindControl("textBoxPONum")).Text;
                    int poNum = 0;
    
                    if (!Int32.TryParse(poNumStr, out poNum))
                        throw new InvalidDataException($"Error: Couldn't parse PONum ('{poNumStr}')");
    
                    //Amount
                    string amountStr = ((TextBox)GridViewItem.Rows[rowIndex].FindControl("textBoxAmount")).Text;
                    decimal amount = 0;
    
                    if (!Decimal.TryParse(amountStr, out amount))
                        throw new InvalidDataException($"Error: Couldn't parse Amount ('{amountStr}')");
    
                    //Quantity
                    string quantityStr = ((TextBox)GridViewItem.Rows[rowIndex].FindControl("textBoxQuantity")).Text;
                    int quantity = 0;
    
                    if (!Int32.TryParse(quantityStr, out quantity))
                        LogMsg($"Error: Couldn't parse Quantity ('{quantityStr}')");
    
                    //ToDo: change as desired
                    System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo("en-US");
                    //System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
    
                    //OrderedOn
                    string orderedOnStr = ((TextBox)GridViewItem.Rows[rowIndex].FindControl("textBoxOrderedOn")).Text;
                    DateTime orderedOn = new DateTime(month: 1, day: 1, year: 1753, hour: 12, minute: 0, second: 0); //set to min value
    
                    LogMsg($"    orderedOnStr: {orderedOnStr}");
    
                    //use UTC time
                    if (!DateTime.TryParseExact(orderedOnStr, "MM/dd/yyyy h:mm:ss tt", provider, System.Globalization.DateTimeStyles.AdjustToUniversal, out orderedOn))
                        throw new InvalidDataException($"Error: Couldn't parse OrderedOn ('{orderedOnStr}'). Required format: MM/dd/yyyy h:mm:ss AM or MM/dd/yyyy h:mm:ss PM");
    
                    //ReceivedOn
                    string receivedOnStr = ((TextBox)GridViewItem.Rows[rowIndex].FindControl("textBoxReceivedOn")).Text;
                    DateTime receivedOn = new DateTime(month: 1, day: 1, year: 1753, hour: 12, minute: 0, second: 0); //set to min value
    
                    //use UTC time
                    if (!DateTime.TryParseExact(receivedOnStr, "MM/dd/yyyy h:mm:ss tt", provider, System.Globalization.DateTimeStyles.AdjustToUniversal, out receivedOn))
                        throw new InvalidDataException($"Error: Couldn't parse ReceivedOn ('{receivedOnStr}'). Required format: MM/dd/yyyy h:mm:ss AM or MM/dd/yyyy h:mm:ss PM");
    
                    //TechNotes
                    string techNotes = ((TextBox)GridViewItem.Rows[rowIndex].FindControl("textBoxTechNotes")).Text;
    
                    //DetailItemId
                    string itemDetailIdStr = ((TextBox)GridViewItem.Rows[rowIndex].FindControl("textBoxitemDetailId")).Text;
                    int itemDetailId = 0;
    
                    if (!Int32.TryParse(itemDetailIdStr, out itemDetailId))
                        throw new InvalidDataException($"Error: Couldn't parse ItemDetailId ('{itemDetailIdStr}')");
    
                    for (int i = 0; i < _dt.Rows.Count; i++)
                    {
                        string lineOutput = string.Empty;
                        for (int j = 0; j < _dt.Columns.Count; j++)
                        {
                            if (!String.IsNullOrEmpty(lineOutput))
                                lineOutput += $" {_dt.Rows[i][j]?.ToString()}";
                            else
                                lineOutput = _dt.Rows[i][j]?.ToString();
                        }
    
                        LogMsg($"lineOutput[{i}]: {lineOutput}");
                    }
    
                    int rowsAffected = OrderItemsUpdate(id, description, poNum, amount, quantity, orderedOn, receivedOn, techNotes, itemDetailId);
                    LogMsg($"    OrderItemsUpdate rowsAffected: {rowsAffected}");
    
                    GridViewItem.EditIndex = -1;
    
                    OrderItemsGetAndBindData();
    
                    //Response.Write($"<script>alert('Rows Updated: {rowsAffected}')</script>");
                }
            }
    
            protected void GridViewItem_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                //LogMsg($"GridViewItem_RowDataBound e.Row.RowIndex: '{e.Row.RowIndex}' RowType: '{e.Row.RowType}");
    
            }
    
            protected void GridViewItem_RowDeleting(object sender, GridViewDeleteEventArgs e)
            {
                LogMsg($"GridViewItem_RowDeleting e.RowIndex: '{e.RowIndex}'");
            }
    
            protected void GridViewItem_RowEditing(object sender, GridViewEditEventArgs e)
            {
                LogMsg($"GridViewItem_RowEditing e.NewEditIndex: '{e.NewEditIndex}'");
    
                GridView gv = (GridView)sender;
    
                gv.EditIndex = e.NewEditIndex;
                gv.DataBind();
            }
    
            protected void GridViewItem_RowUpdated(object sender, GridViewUpdatedEventArgs e)
            {
                LogMsg($"GridViewItem_RowUpdated affectedRows: '{e.AffectedRows}'");
            }
    
            protected void GridViewItem_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
                LogMsg($"GridViewItem_RowUpdating e.RowIndex: '{e.RowIndex}'");
    
                GridView gv = (GridView)sender;
    
                //GridViewRow row = gv.Rows[e.RowIndex];
                //int id = Convert.ToInt32(gv.DataKeys[e.RowIndex].Values[0]);
            }
    
            protected void GridViewItem_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
            {
                LogMsg($"GridViewItem_SelectedIndexChanging e.NewSelectedIndex: '{e.NewSelectedIndex}'");
            }
    
            protected void GridViewItem_SelectedIndexChanged(object sender, EventArgs e)
            {
                LogMsg($"GridViewItem_SelectedIndexChanged e: '{e?.ToString()}'");
            }
    
            // The id parameter name should match the DataKeyNames value set on the control
            public void GridViewItem_UpdateItem(int id)
            {
                LogMsg($"GridViewItem_UpdateItem id: '{id}'");
    
            }
    
            private int OrderItemsGetAndBindData()
            {
                //clear existing
                _dt.Clear();
    
                using (SqlDataAdapter da = new SqlDataAdapter("SELECT Id, Description, PONum, Amount, Quantity, OrderedOn, ReceivedOn, TechNotes, ItemDetailId FROM OrderItems Order By Id", ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString))
                {
                    int rowsAffected = da.Fill(_dt);
    
                    GridViewItem.DataSource = _dt;
                    GridViewItem.DataBind();
    
                    return rowsAffected;
                }
            }
    
            private int OrderItemsUpdate(int id, string description, int poNum, decimal amount, int quantity, DateTime orderedOn, DateTime receivedOn, string techNotes, int itemDetailId)
            {
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString))
                {
                    //open
                    conn.Open();
    
                    //square brackets are only necessary if column name is reserved word or contains spaces
                    using (SqlCommand cmd = new SqlCommand("UPDATE OrderItems SET [Description] = @description, [PONum] = @poNum, [Amount] = @amount, [Quantity] = @quantity, [OrderedOn] = @orderedOn, [ReceivedOn] = @receivedOn, [TechNotes] = @techNotes, [ItemDetailId] = @itemDetailId where Id = @id ", conn))
                    {
                        //add parameters and values
                        cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
    
                        if (!String.IsNullOrEmpty(description))
                            cmd.Parameters.Add("@description", SqlDbType.VarChar).Value = description;
                        else
                            cmd.Parameters.Add("@description", SqlDbType.VarChar).Value = DBNull.Value;
    
                        cmd.Parameters.Add("@poNum", SqlDbType.Int).Value = poNum;
                        cmd.Parameters.Add("@amount", SqlDbType.Decimal).Value = amount;
                        cmd.Parameters.Add("@quantity", SqlDbType.Int).Value = quantity;
                        cmd.Parameters.Add("@orderedOn", SqlDbType.DateTime).Value = orderedOn;
                        cmd.Parameters.Add("@receivedOn", SqlDbType.DateTime).Value = receivedOn;
    
                        if (!String.IsNullOrEmpty(techNotes))
                            cmd.Parameters.Add("@techNotes", SqlDbType.VarChar).Value = techNotes;
                        else
                            cmd.Parameters.Add("@techNotes", SqlDbType.VarChar).Value = DBNull.Value;
    
                        cmd.Parameters.Add("@itemDetailId", SqlDbType.Int).Value = itemDetailId;
    
                        int rowsAffected = cmd.ExecuteNonQuery();
    
                        return rowsAffected;
                    }
                }
            }
        }
    }
    

    Resources

    Login or Signup to reply.
  2. The following shows how one can use GridView with SqlDataSource in an ASP.NET Web Application (.NET Framework) project to display and update data.

    VS 2022:

    Add Web Form to project

    • In VS menu, click Project
    • Select Add New Item…
    • On left side, expand "Web". Select Web Form (name: default.aspx)
    • Click Add

    Open Solution Explorer

    • In VS menu, click View
    • Select Solution Explorer

    detail.aspx:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="detail.aspx.cs" EnableSessionState="true" Inherits="GridViewTestA.detail" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
             
            <div style="position:absolute;left:50px; top:100px">
                <asp:GridView ID="GridViewItemDetail" runat="server" 
                    AllowPaging="true" AllowSorting="True"
                    AlternatingRowStyle-BorderStyle="Solid" AlternatingRowStyle-BackColor="White" 
                    AlternatingRowStyle-ForeColor="#6f263d"  AlternatingRowStyle-CssClass="fancylink" 
                    AutoGenerateColumns="false" 
                    AutoGenerateSelectButton="False"
                    BorderStyle="None" 
                    CellPadding="7" CellSpacing="0" 
                    ConflictDetection="true"
                    DataKeyNames="Id"
                    DataSourceID="ItemDetailDataSource"
                    Font-Size="Small" RowStyle-BackColor="#63666A" 
                    HeaderStyle-BackColor="#6f263d" 
                    HeaderStyle-ForeColor="White" 
                    HorizontalAlign="Center" 
                    OnPageIndexChanging="GridViewItemDetail_PageIndexChanging"
                    OnRowCancelingEdit="GridViewItemDetail_RowCancelingEdit"
                    OnRowCommand ="GridViewItemDetail_RowCommand"
                    OnRowDataBound="GridViewItemDetail_RowDataBound"
                    OnRowDeleting="GridViewItemDetail_RowDeleting"
                    PageSize="10" 
                    PagerStyle-BackColor="#6f263d" PagerStyle-CssClass="fancylink" PagerStyle-ForeColor="White" 
                    PagerSettings-FirstPageText="First Page&nbsp;&nbsp;&nbsp;"  
                    PagerSettings-Mode="NextPrevious" PagerSettings-NextPageText="Next Page" 
                    PagerSettings-LastPageText="End" PagerSettings-PreviousPageText="Previous Page" 
                    PagerStyle-HorizontalAlign="Center" PagerStyle-Width="20%" 
                    RowStyle-BorderStyle="None" RowStyle-ForeColor="White" 
                    SelectedRowStyle-BackColor="#D3D0C8" SelectedRowStyle-ForeColor="Black" 
                    ShowHeaderWhenEmpty="false" >
                    
                    <Columns>
                        <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-HorizontalAlign="Center"  ReadOnly="true" Visible="True" />
                        <asp:BoundField DataField="Description" HeaderText="Description" ItemStyle-HorizontalAlign="Center" />
                        <asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer" ItemStyle-HorizontalAlign="Center" />
                        <asp:BoundField DataField="ProductIdentifier" HeaderText="ProductIdentifier" ItemStyle-HorizontalAlign="Center" />
                        <asp:BoundField DataField="Amount" HeaderText="Amount" ItemStyle-HorizontalAlign="Left" />
                        <asp:BoundField DataField="QuantityAvailable" HeaderText="QuantityAvailable" ItemStyle-HorizontalAlign="Center" />
                        
                        <asp:TemplateField HeaderText="" ItemStyle-HorizontalAlign="Center">
                            <ItemTemplate>
                                <asp:LinkButton ID="btnEdit" runat="server" Text='Edit' ControlStyle-Width ="40" ControlStyle-Height="40" CommandName="Edit" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' OnCommand="btnEdit_Command" />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:LinkButton ID="btnUpdate" runat="server" Text="Update" CommandName="Update" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' OnCommand="btnUpdate_Command" ItemStyle-HorizontalAlign="Center" />
                                <asp:LinkButton ID="btnCancel" runat="server" Text="Cancel" CommandName="Cancel" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' OnCommand="btnCancel_Command" ItemStyle-HorizontalAlign="Center" />
                            </EditItemTemplate>
                        </asp:TemplateField> 
    
                    </Columns>
                </asp:GridView>
            </div>
    
            <asp:SqlDataSource id="ItemDetailDataSource"
                SelectCommand="SELECT Id, Description, Manufacturer, ProductIdentifier, Amount, QuantityAvailable FROM ItemDetail Where Id = @Id;"
                InsertCommand="INSERT INTO ItemDetail (Description, Manufacturer, ProductIdentifier, Amount, QuantityAvailable) VALUES (@Description, @Manufacturer, @ProductIdentifier, @Amount, @QuantityAvailable);"
                UpdateCommand="UPDATE ItemDetail SET [Description] = @Description, [Manufacturer] = @Manufacturer, [ProductIdentifier] = @ProductIdentifier, [Amount] = @Amount, [QuantityAvailable] = @QuantityAvailable Where Id = @Id;"
                ConnectionString="<%$ ConnectionStrings:dbConnection %>"
                runat="server" >
    
          <InsertParameters>
              <asp:Parameter Name="Id" Type="Int32" />
              <asp:Parameter Name="Description" Type="String" />
              <asp:Parameter Name="Manufacturer" Type="String" />
              <asp:Parameter Name="ProductIdentifier" Type="String" />
              <asp:Parameter Name="Amount" Type="Decimal" />
              <asp:Parameter Name="QuantityAvailable" Type="Int32" />
          </InsertParameters>
    
          <UpdateParameters>
              <asp:Parameter Name="Id" Type="Int32" />
              <asp:Parameter Name="Description" Type="String" />
              <asp:Parameter Name="Manufacturer" Type="String" />
              <asp:Parameter Name="ProductIdentifier" Type="String" />
              <asp:Parameter Name="Amount" Type="Decimal" />
              <asp:Parameter Name="QuantityAvailable" Type="Int32" />
          </UpdateParameters>
      </asp:SqlDataSource>
        </form>
    </body>
    </html>
    

    detail.aspx.cs

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Security.Policy;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace GridViewTestA
    {
        public partial class detail : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                Page page = (Page)sender;
                
                if (!page.IsPostBack)
                {
                    //option 1
                    //if 'Id' was passed as a GET parameter, use this. see 'default.aspx.cs'
                    string idStr = page.Request.QueryString["Id"];
                    LogMsg($"detail.aspx.cs id: {idStr}");
    
                    //option 2
                    //if 'Id' was passed as a session variable, use this instead. see 'default.aspx.cs'
                    //string idStr = Session["Id"]?.ToString();
                    //LogMsg($"detail.aspx.cs idStr: {idStr}");
    
                    int id = 0;
                    if (Int32.TryParse(idStr, out id))
                    {
                        //create new instance
                        Parameter pId = new Parameter() { Name = "Id", DbType = System.Data.DbType.Int32, DefaultValue = idStr };
                        if (!ItemDetailDataSource.SelectParameters.Contains(pId))
                        {
                            ItemDetailDataSource.SelectCommand = $"SELECT Id, Description, Manufacturer, ProductIdentifier, Amount, QuantityAvailable FROM ItemDetail Where Id = @Id";
                            ItemDetailDataSource.SelectParameters.Add(pId);
                        }
                    }
                    else
                    {
                        throw new InvalidDataException($"Error: Couldn't parse Id ('{idStr}')");
                    }
                }
            }
    
            private void LogMsg(string msg, bool includeTimeStamp = true)
            {
                if (includeTimeStamp)
                    msg = $"{DateTime.Now.ToString("HH:mm:ss.fff")} - {msg}";
    
                //ToDo: add desired code
                Debug.WriteLine(msg);
            }
    
            protected void btnUpdate_Command(object sender, CommandEventArgs e)
            {
    
            }
    
            protected void btnCancel_Command(object sender, CommandEventArgs e)
            {
    
            }
    
            protected void btnEdit_Command(object sender, CommandEventArgs e)
            {
    
            }
    
            protected void GridViewItemDetail_PageIndexChanging(object sender, GridViewPageEventArgs e)
            {
    
            }
    
            protected void GridViewItemDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
    
            }
    
            protected void GridViewItemDetail_RowCommand(object sender, GridViewCommandEventArgs e)
            {
    
            }
    
            protected void GridViewItemDetail_RowDataBound(object sender, GridViewRowEventArgs e)
            {
    
            }
    
            protected void GridViewItemDetail_RowDeleting(object sender, GridViewDeleteEventArgs e)
            {
    
            }
        }
    }
    

    Web.config

    <?xml version="1.0" encoding="utf-8"?>
    <!--
      For more information on how to configure your ASP.NET application, please visit
      https://go.microsoft.com/fwlink/?LinkId=169433
      -->
    <configuration>
      <connectionStrings>
        <add name="dbConnection" connectionString="Server=.SQLExpress;Database=Test;User Id=testUser123;Password=NotMyRealPassword;" providerName="System.Data.SqlClient" />
      </connectionStrings>
       
      <!-- additional settings go here -->
    
    </configuration>
    

    The following tables and data were used for testing. The table design isn’t optimal, but is sufficient for demonstration of the code in this post. If unfamiliar with database table design, read about database normalization.

    Table: ItemDetail

    CREATE TABLE ItemDetail (
    Id int NOT NULL IDENTITY(1,1), 
    Description varchar(75) NOT NULL, 
    Manufacturer varchar(125) NOT NULL, ProductIdentifier varchar(75) NOT NULL, 
    Amount decimal(18,2) NOT NULL, QuantityAvailable int NOT NULL, 
    UpdatedOn datetime, 
    CONSTRAINT PK_ItemDetail_Id PRIMARY KEY(ID));
    

    Insert Test Data: ItemDetail

    INSERT INTO ItemDetail (Description, Manufacturer, ProductIdentifier, Amount, QuantityAvailable, UpdatedOn) VALUES ('HP Envy Laptop 17t-da000', 'HP', '8Z288AV_1', 1299.99, 5, GETDATE());
    INSERT INTO ItemDetail (Description, Manufacturer, ProductIdentifier, Amount, QuantityAvailable, UpdatedOn) VALUES ('HP Spectre x360 2-in-1 Laptop 16t-aa000', 'HP', '7M3L6AV_1', 1599.99, 5, GETDATE());
    INSERT INTO ItemDetail (Description, Manufacturer, ProductIdentifier, Amount, QuantityAvailable, UpdatedOn) VALUES ('Alienware m18 R2 Gaming Laptop', 'Dell', 'useashbtsm18r2grtn', 1899.99, 2, GETDATE());
    INSERT INTO ItemDetail (Description, Manufacturer, ProductIdentifier, Amount, QuantityAvailable, UpdatedOn) VALUES ('XPS 15', 'Dell', 'usexcpbts9530gvgy', 1359.00, 4, GETDATE());
    

    Table: OrderItems

    CREATE TABLE OrderItems (
    Id int NOT NULL IDENTITY(1,1), 
    Description varchar(75), 
    PONum int, 
    Amount decimal(18,2), 
    Quantity int, 
    OrderedOn datetime, 
    ReceivedOn datetime, 
    TechNotes varchar(125), 
    ItemDetailId int NOT NULL, 
    CONSTRAINT PK_OrderItems_Id PRIMARY KEY(Id),
    CONSTRAINT FK_OrderItems_ItemDetail_Id FOREIGN KEY (ItemDetailId) REFERENCES ItemDetail(Id));
    

    Insert Test Data: OrderItems

    INSERT INTO OrderItems (Description, PONum, Amount, Quantity, OrderedOn, ReceivedOn, TechNotes, ItemDetailId) VALUES ((SELECT Description FROM ItemDetail WHERE Id = 2) , 123, (SELECT Amount FROM ItemDetail WHERE Id = 2), 1, '2024-12-10 18:00:00', '2024-12-14 15:00:00', 'test 1', 2);
    INSERT INTO OrderItems (Description, PONum, Amount, Quantity, OrderedOn, ReceivedOn, TechNotes, ItemDetailId) VALUES ((SELECT Description FROM ItemDetail WHERE Id = 3) , 124, (SELECT Amount FROM ItemDetail WHERE Id = 3), 1, '2024-12-12 12:00:00', '2024-12-14 16:00:00', 'test 2', 3);
    

    Resources:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search