我的问题分为两部分。请耐心等待...只是学习这些东西。
我有一个允许编辑的 GridView,这将更新数据库表。问题#1 是我似乎无法从后面的代码中的 GridView 获取值。我不断收到错误。我尝试了几种不同的方法,但我完全遇到了障碍。
这是 ASP.NET 标记:
<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 "
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>
在我的代码后面:
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();
}
我已经确认前两行确实让我找到了正确的行(
itemNum
):
GridViewRow row = ItemView.SelectedRow;
int itemNum = Convert.ToInt16(ItemView.DataKeys[e.RowIndex].Values[0]);
但随后它就破裂了。当我运行它时,我得到:
未将对象引用设置为对象的实例。
描述:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其在代码中的来源的更多信息。异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例。
来源错误:
第 116 行:int itemNum = Convert.ToInt16(ItemView.DataKeys[e.RowIndex].Values[0]);
117号线:
第 118 行: string poNum = ((System.Web.UI.WebControls.TextBox)row.FindControl("txt_poNum")).Text;
所以这是第一个问题。
第二个问题是有人可以编辑 gridview 行中的多个填充,但他们不必全部编辑。 他们可能会输入 PONumber 和金额,但不会输入技术说明或接收日期。 我需要一种优雅的方法来检查空字段以构建更新语句。你可以看到我所做的,这是根据我在网上找到的东西建模的。有没有更好的方法可以循环执行此操作?
预先感谢您能给我的任何帮助。我要拔头发了!
尝试以下操作:
VS 2022:
创建一个新的
ASP.NET Web Application (.NET Framework)
选择
ASP.NET Web Application (.NET Framework)
单击下一步
输入所需的项目名称(例如:GridViewTestA)
选择所需的框架(例如:.NET Framework 4.8)
单击创建
在“创建新的 ASP.NET Web 应用程序”表单中,选择空。
如果您使用“http”而不是“https”,请在“高级”下取消选中“配置 HTTPS”。
单击创建
将 Web 表单添加到项目
打开解决方案资源管理器
默认.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 "
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>
默认.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;
}
}
}
}
}
资源