[需要帮助]可编辑Gridview无法更新单行中的数据 [英] [Need Help] Editable Gridview cannot update data in single row
问题描述
你好,
我现在正在网站开发.我使用了某人发布的示例.但是,编译后,我的可编辑GridView无法更新,但是删除,编辑,插入数据都可以正常工作.我认为问题应该出在其.cs文件中的"DataBound"上.
我想让此GridView用于将每行中的数据更新到SQL表.当我单击更新按钮时,收到以下错误消息:异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例.任何人都可以帮助我吗?
现在,为方便起见,我发布了代码.
Default.cs文件中的代码
Hi there,
I am now to website development. I used a example posted by someone. However, after compilation my editable GridView cannot update, but deleting, editing, Inserting data all work well. I think the problem should be on the "DataBound" in its .cs file.
I want let this GridView works on Updating data in each row to SQL table. When I click the Update button, I get this error message: Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Any one can help me out?
Now I post my code for your convenience.
code in Default.cs file
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class GridViewInsertEditUpdateDelete : System.Web.UI.Page
{
CustomersCls customer = new CustomersCls();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
FillCustomerInGrid();
}
private void FillCustomerInGrid()
{
DataTable dtCustomer = customer.Fetch();
if (dtCustomer.Rows.Count > 0)
{
GridView1.DataSource = dtCustomer;
GridView1.DataBind();
}
else
{
dtCustomer.Rows.Add(dtCustomer.NewRow());
GridView1.DataSource = dtCustomer;
GridView1.DataBind();
int TotalColumns = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = TotalColumns;
GridView1.Rows[0].Cells[0].Text = "No Record Found";
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtNewOrderID = (TextBox)GridView1.FooterRow.FindControl("txtNewOrderID");
DropDownList cmbNewPart = (DropDownList)GridView1.FooterRow.FindControl("cmbNewPart");
DropDownList cmbNewStage = (DropDownList)GridView1.FooterRow.FindControl("cmbNewStage");
DropDownList cmbNewOperation = (DropDownList)GridView1.FooterRow.FindControl("cmbNewOperation");
TextBox txtNewUpdateDate = (TextBox)GridView1.FooterRow.FindControl("txtNewUpdateDate");
TextBox txtNewUpdater = (TextBox)GridView1.FooterRow.FindControl("txtNewUpdater");
customer.Insert(Convert.ToInt32(txtNewOrderID.Text), cmbNewPart.SelectedValue,
cmbNewStage.SelectedValue, cmbNewOperation.SelectedValue,
txtNewUpdateDate.Text, Convert.ToInt32(txtNewUpdater.Text));
FillCustomerInGrid();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
FillCustomerInGrid();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
customer.Delete(Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0].ToString()));
FillCustomerInGrid();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
FillCustomerInGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtOrderID = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtOrderID");
DropDownList cmbPart = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbPart");
DropDownList cmbStage = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbStage");
DropDownList cmbOperation = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbOperation");
TextBox txtUpdateDate = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtUpdateDate");
TextBox txtUpdater = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtUpdater");
customer.Update(Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0].ToString()),
Convert.ToInt32(txtOrderID.Text), cmbPart.SelectedValue,
cmbStage.SelectedValue, cmbOperation.SelectedValue,
txtUpdateDate.Text, Convert.ToInt32(txtUpdater.Text));
GridView1.EditIndex = -1;
FillCustomerInGrid();
}
}
还有Default.aspx中的代码
And the code in Default.aspx
<<pre lang="xml">%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="GridViewInsertEditUpdateDelete" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Code" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDataBound="GridView1_RowDataBound" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand" ShowFooter="True" OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="OrderID" SortExpression="OrderID">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text=''<%# Eval("OrderID") %>''></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewOrderID" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text=''<%# Bind("OrderID") %>''></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Part">
<EditItemTemplate>
<asp:DropDownList ID="cmbPart" runat="server" SelectedValue=''<%# Eval("Part") %>''>
<asp:ListItem Value="Top Rail" Text="Top Rail"></asp:ListItem>
<asp:ListItem Value="Bottom Rail" Text="Bottom Rail"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbPart" runat="server" Text=''<%# Eval("Part") %>''></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="cmbNewPart" runat="server" >
<asp:ListItem Selected="True" Value="Top Rail" Text="Top Rail"></asp:ListItem>
<asp:ListItem Value="Bottom Rail" Text="Bottom Rail"></asp:ListItem> </asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Stage">
<EditItemTemplate>
<asp:DropDownList ID="cmbStage" runat="server" SelectedValue=''<%# Eval("Stage") %>''>
<asp:ListItem Value="Design" Text="Design"></asp:ListItem>
<asp:ListItem Value="Manufacturing" Text="Manufacturing"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbStage" runat="server" Text=''<%# Eval("Stage") %>''></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="cmbNewStage" runat="server" >
<asp:ListItem Selected="True" Value="Design" Text="Design"></asp:ListItem>
<asp:ListItem Value="Manufacturing" Text="Manufacturing"></asp:ListItem> </asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Operation">
<EditItemTemplate>
<asp:DropDownList ID="cmbOperation" runat="server" SelectedValue=''<%# Eval("Operation") %>''>
<asp:ListItem Value="Machining" Text="Machining"></asp:ListItem>
<asp:ListItem Value="Coloring" Text="Coloring"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbOperation" runat="server" Text=''<%# Eval("Operation") %>''></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="cmbNewOperation" runat="server" >
<asp:ListItem Selected="True" Value="Machining" Text="Machining"></asp:ListItem>
<asp:ListItem Value="Coloring" Text="Coloring"></asp:ListItem> </asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UpdateDate">
<EditItemTemplate>
<asp:TextBox ID="txtUpdateDate" runat="server" Text=''<%# Bind("UpdateDate") %>''></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewUpdateDate" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text=''<%# Bind("UpdateDate") %>''></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Updater"> <EditItemTemplate>
<asp:TextBox ID="txtUpdater" runat="server" Text=''<%# Eval("Updater") %>''></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewUpdater" runat="server"></asp:TextBox> </FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text=''<%# Bind("Updater") %>''></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
</Columns>
</asp:GridView>
<br />
<br />
<br />
</div>
</form>
</body>
</html>
CustomerCls.cs代码
The CustomersCls.cs code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
/// <summary>
/// Summary description for ClsCustomer
/// </summary>
public class CustomersCls
{
private string cnstr = ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString"].ConnectionString;
private string sql;
public CustomersCls()
{
//
// TODO: Add constructor logic here
//
}
public void Insert(int OrderID, string Part, string Stage, string Operation, string UpdateDate, int Updater)
{
string sql = "Insert Into Progress (OrderID, Part, Stage, Operation, UpdateDate, Updater) Values (''" + OrderID + "'', ''" + Part
+ "'' , ''" + Stage + "'', ''" + Operation + "'', ''" + UpdateDate + "'', ''" + Updater + "'')";
SqlConnection conn = new SqlConnection(cnstr);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
public DataTable Fetch()
{
string sql = "Select * From Progress";
SqlDataAdapter da = new SqlDataAdapter(sql, cnstr);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
public void Update(int CustomerCode, int OrderID, string Part, string Stage, string Operation, string UpdateDate, int Updater)
{
string sql = "UPDATE Progress SET OrderID = ''" + OrderID + "'', Part = ''" + Part
+ "'', Stage= ''" + Stage + "'', Operation = ''" + Operation
+ "'', UpdateDate = ''" + UpdateDate + "'', Updater = ''" + Updater
+ "'' Where Code=" + CustomerCode;
SqlConnection conn = new SqlConnection(cnstr);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
public void Delete(int CustomerCode)
{
string sql = "Delete Progress Where Code=" + CustomerCode;
SqlConnection conn = new SqlConnection(cnstr);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
// public DataTable FetchCustomerType()
// {
// string sql = "Select Type From Progress";
// SqlDataAdapter da = new SqlDataAdapter(sql, cnstr);
// DataTable dt = new DataTable();
// da.Fill(dt);
// return dt;
// }
}
推荐答案
您在GridView1_RowUpdating事件中使用了TextBox txtOrderID = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtOrderID");
.但是您在设计中没有txtOrderID
控件.因此,您收到System.NullReferenceException: Object reference not set to an instance of an object
错误.请更正该内容.
You have usedTextBox txtOrderID = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtOrderID");
in GridView1_RowUpdating event. But you don''t havetxtOrderID
control in design. So, you are gettingSystem.NullReferenceException: Object reference not set to an instance of an object
error. Please correct that.
如果它是空引用,则以下任何一条语句都会失败:
if it is a nullreference any of the next statements fails:
TextBox txtOrderID = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtOrderID");
DropDownList cmbPart = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbPart");
DropDownList cmbStage = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbStage");
DropDownList cmbOperation = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbOperation");
TextBox txtUpdateDate = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtUpdateDate");
TextBox txtUpdater = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtUpdater")
如果FindControl找不到控件,则其值为NULL.
调试这部分代码并添加Watch项目,以查看哪个为NULL
If FindControl cannot find the control it''s value will be NULL.
Debug this part of code and add Watch items to see which one is NULL
GridView1.DataKeys [e.RowIndex] .Value.ToString())
进行更改以希望找到解决方案
GridView1.DataKeys[e.RowIndex].Value.ToString())
Do changes hope you will find your solution
这篇关于[需要帮助]可编辑Gridview无法更新单行中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!