我在网格上进行更新操作...在AJAX更新面板中。它没有获取列数据......(!IsPostBack)东西似乎根本没有工作......
这是Grid Mark Up
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="List.aspx.cs" Inherits="WebApplication1._3_Tier.List" %>
<!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 id="Head1" runat="server">
<style type="text/css">
body
{
font-family: Arial, Trebuchet Ms;
font-size: 10pt;
}
.style3
{
width: 182px;
}
</style>
<script type="text/javascript">
function x() {
var firstName = document.getElementById("<%=txtFirstName.ClientID%>").value.trim();
var lastName = document.getElementById("<%=txtLastName.ClientID%>").value.trim();
var Age = document.getElementById("<%=txtAge.ClientID%>").value.trim();
if (firstName == "") {
alert('firstName cannot be null')
return false;
}
if (lastName == "") {
alert('lastName cannot be null')
return false;
}
if (Age == "") {
alert('Age cannot be null')
return false;
}
return true;
}
</script>
<title>List Records</title>
</head>
<body>
<h3>
Demo: 3-Tier Architecture</h3>
<div>
<form id="form11" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<p>
<asp:Label ID="lblMessage" runat="Server" ForeColor="red" EnableViewState="False"></asp:Label>
</div>
<table>
<tr>
<td>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
DataKeyNames="Id" AutoGenerateEditButton="True" AutoGenerateColumns="False" OnRowEditing="EditRecord"
OnRowUpdating="UpdateRecord" OnRowCancelingEdit="CancelRecord" OnRowDeleting="DeleteRecord"
AllowPaging="True" AllowSorting="true" PageSize="5" OnPageIndexChanging="ChangePage"
OnSorting="SortRecords">
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2ff1BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
<asp:TemplateField HeaderText="First Name">
<EditItemTemplate>
<asp:TextBox ID="txtFName" runat="server" Width="75px" Text='<%# Bind("FirstName")%>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblFName" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
<ItemTemplate>
<%# Eval("LastName") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLName" runat="Server" Text='<%# Eval("LastName") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age" SortExpression="Age">
<ItemTemplate>
<%# Eval("Age") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAge" runat="Server" Text='<%# Eval("Age") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to Delete?')">
<asp:LinkButton ID="lnBD" runat="server" Text="Delete" CommandName="Delete"></asp:LinkButton>
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<br />
<asp:GridView ID="GridView2" runat="server" OnRowUpdating="UpdateRecord1" OnRowEditing="GridView2_RowEditing">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="First Name">
<EditItemTemplate>
<asp:TextBox ID="txtFName" runat="server" Width="75px" Text='<%# Bind("FirstName")%>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblFName" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView1" />
</Triggers>
</asp:UpdatePanel>
</td>
<td>
<asp:UpdatePanel ID="UpdatePanel3" runat="server">
<ContentTemplate>
<div>
<p>
<asp:Label ID="Label1" runat="Server" ForeColor="red" EnableViewState="False"></asp:Label>
<table style="border: 2px solid #cccccc;">
<tr style="background-color: #507CD1; color: White;">
<th colspan="2">
Add Records
</th>
</tr>
<tr>
<td>
First Name:
</td>
<td class="style3">
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Last Name:
</td>
<td class="style3">
<asp:TextBox ID="txtLastName" runat="Server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Age:
</td>
<td class="style3">
<asp:TextBox ID="txtAge" runat="Server" Columns="4"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td class="style3">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="AddRecords" OnClientClick="if (!x()) { return false; }" />
</td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
</table>
</form>
</body>
</html>
这是更新操作的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BLL;
namespace WebApplication1._3_Tier
{
public partial class List : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindGrid();
}
/// <summary>
/// Fired when Cancel button is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void CancelRecord(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGrid();
}
/// <summary>
/// Fires when Edit button is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void EditRecord(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
/// <summary>
/// Fires when Update button is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void UpdateRecord(object sender, GridViewUpdateEventArgs e)
{
int personID = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
int intResult = 0;
GridViewRow row = GridView1.Rows[e.RowIndex];
TextBox tFN = (TextBox)row.FindControl("txtFName");
TextBox tLN = (TextBox)row.FindControl("txtLName");
TextBox tAge = (TextBox)row.FindControl("txtAge");
// instantiate BAL
PersonBAL3 pBAL = new PersonBAL3();
try
{
intResult = pBAL.Update(personID, tFN.Text, tLN.Text, int.Parse(tAge.Text));
if (intResult > 0)
lblMessage.Text = "Record Updated Successfully.";
else
lblMessage.Text = "Record couldn't updated";
}
catch (Exception ee)
{
lblMessage.Text = ee.Message.ToString();
}
finally
{
pBAL = null;
}
GridView1.EditIndex = -1;
// Refresh the list
BindGrid();
}
/// <summary>
/// fires when Delete button is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
{
int personID = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
// instantiate BAL
PersonBAL3 pBAL = new PersonBAL3();
try
{
pBAL.Delete(personID);
lblMessage.Text = "Record Deleted Successfully.";
}
catch (Exception ee)
{
lblMessage.Text = ee.Message.ToString();
}
finally
{
pBAL = null;
}
GridView1.EditIndex = -1;
// Refresh the list
BindGrid();
}
/// <summary>
/// Fires when page links are clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ChangePage(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
// Refresh the list
BindGrid();
}
/// <summary>
/// Fires when Columns heading are clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void SortRecords(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = GridDataSource();
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = GetSortExpression(e);
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
#region Private Methods
/// <summary>
/// Bind the gridview
/// </summary>
private void BindGrid()
{
GridView1.DataSource = GridDataSource();
GridView1.DataBind();
}
/// <summary>
/// Get GridView DataSource
/// </summary>
private DataTable GridDataSource()
{
PersonBAL3 p = new PersonBAL3();
DataTable dTable = new DataTable();
try
{
dTable = p.Load();
}
catch (Exception ee)
{
lblMessage.Text = ee.Message.ToString();
}
finally
{
p = null;
}
return dTable;
}
/// <summary>
/// Get sort expression for the gridview
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
private string GetSortExpression(GridViewSortEventArgs e)
{
string sortDirection = string.Empty;
// if clicked on the same column twice then let it toggle the sort order, else reset to ascending
if (ViewState["SortExpression"] != null)
{
if (!ViewState["SortExpression"].ToString().Equals(e.SortExpression.ToLower()))
{
ViewState["SortDirection"] = null;
}
}
if (ViewState["SortDirection"] != null)
{
if (ViewState["SortDirection"].ToString().Equals("ASC"))
{
sortDirection = "DESC";
ViewState["SortDirection"] = "DESC";
}
else
{
sortDirection = "ASC";
ViewState["SortDirection"] = "ASC";
}
}
else
{
ViewState["SortDirection"] = "ASC";
}
ViewState["SortExpression"] = e.SortExpression.ToLower();
return e.SortExpression + " " + sortDirection;
}
#endregion Private Methods
protected void AddRecords(object sender, EventArgs e)
{
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
int age = Int32.Parse(txtAge.Text);
string lbl = lblMessage.Text;
//Lets validate the page first
if (!Page.IsValid)
return;
int intResult = 0;
// Page is valid, lets go ahead and insert records
// Instantiate BAL object
PersonBAL3 pBAL = new PersonBAL3();
// Instantiate the object we have to deal with
try
{
int i;
pBAL.Insert(firstName, lastName, age, out i);
if (i > 0)
{
lbl = "New record inserted successfully.";
BindGrid();
}
else
lbl = "FirstName [<b>" + firstName + "</b>] alredy exists, try another name";
}
catch (Exception ee)
{
lbl = ee.Message.ToString();
}
finally
{
pBAL = null;
}
}
}
}
问题在于此行;
string firstName = (TextBox)row.FindControl("txtFName").Text;
tFN.Text不会显示数据。我从findControl方法获取datakey,textbox值。 Just Text属性为Blank
我试过这个:
((TextBox)GridView1.Rows[e.Row.RowIndex].Cells[iCellIndex].FindControl("TextBox1")).Text;
和这个
string firstName = GridView1.Rows[0].Cells[2].Text.ToString();
不工作..
我尝试了以下所有帖子的建议:
Why does GridView Rowupdating event not capture the new values of textbox?
http://www.codeproject.com/Questions/627481/fetching-textbox-values-to-gridview-by-clicking-bu
Get TextBox value from GridView cell
http://www.codeproject.com/Questions/156938/How-to-get-value-from-gridview-into-textbox
http://p2p.wrox.com/asp-net-3-5-basics/78346-cant-get-value-textbox-gridview.html
我甚至重新生成了代码..创建了新网格和一切。仍然是同样的错误
...请建议
答案 0 :(得分:0)
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
int id = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox tname = (TextBox)row.FindControl("txtFName");
string firstName =tname.Text;
Or
string firstName = ((TextBox)row.FindControl("txtFName")).Text;
答案 1 :(得分:0)
可能会帮助您将ID作为更新特定ID的数据名称
.cs文件
string id = GridView1.DataKeys[e.RowIndex].Values["ID"].ToString();
TextBox FirstName = GridView1.Rows[e.RowIndex].FindControl("txtFName") as TextBox;
和.aspx页面
<asp:TemplateField HeaderText="First Name">
<EditItemTemplate>
<asp:TextBox ID="txtFName" runat="server" Width="75px" Text='<%# Bind("FirstName")%>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblFName" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
除非您在使用更新按钮之前将FirstName文字设为空,否则这将有效