編輯GridView單元格
說明:單元格擷取焦點,則單元格處于編輯狀态,單元格失去焦點,則立即更新資料庫。采用非Ajax技術。
1、通路Session中的資料
這個例子是使用者使用Session中資料。滑鼠點選編輯GridView單元格。也可以添加一行新記錄。
前台關鍵代碼:
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#DEDFDE" AutoGenerateColumns="False"
BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical"
OnRowDataBound="GridView1_RowDataBound" OnRowCommand="GridView1_RowCommand" OnRowUpdating="GridView1_RowUpdating" ShowFooter="True">
<Columns>
<asp:ButtonField Text="SingleClick" CommandName="SingleClick" Visible="False"/>
<asp:TemplateField HeaderText="Id">
<ItemTemplate>
<asp:Label ID="IdLabel" runat="server" Text='<%# Eval("Id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Task">
<ItemTemplate>
<asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
<asp:TextBox ID="Description" runat="server" Text='<%# Eval("Description") %>' Width="175px" visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Assigned To">
<ItemTemplate>
<asp:Label ID="AssignedToLabel" runat="server" Text='<%# Eval("AssignedTo") %>'></asp:Label>
<asp:DropDownList ID="AssignedTo" runat="server" Visible="false" AutoPostBack="true">
<asp:ListItem></asp:ListItem>
<asp:ListItem>Andy</asp:ListItem>
<asp:ListItem>Betty</asp:ListItem>
<asp:ListItem>Conor</asp:ListItem>
<asp:ListItem>Declan</asp:ListItem>
<asp:ListItem>Eamon</asp:ListItem>
<asp:ListItem>Fergal</asp:ListItem>
<asp:ListItem>Gordon</asp:ListItem>
<asp:ListItem>Helen</asp:ListItem>
<asp:ListItem>Iris</asp:ListItem>
<asp:ListItem>John</asp:ListItem>
<asp:ListItem>Kevin</asp:ListItem>
<asp:ListItem>Lorna</asp:ListItem>
<asp:ListItem>Matt</asp:ListItem>
<asp:ListItem>Nora</asp:ListItem>
<asp:ListItem>Olive</asp:ListItem>
<asp:ListItem>Peter</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="StatusLabel" runat="server" Text='<%# Eval("Status") %>'></asp:Label>
<asp:DropDownList ID="Status" runat="server" Visible="false" AutoPostBack="true">
<asp:ListItem>Pending</asp:ListItem>
<asp:ListItem>In Progress</asp:ListItem>
<asp:ListItem>Complete</asp:ListItem>
<asp:ListItem>Cancelled</asp:ListItem>
<asp:ListItem>Suspended</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#F7F7DE" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<FooterStyle BackColor="#6B696B" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
背景全部代碼:
#region Directives
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;
#endregion
public partial class GridViewEditCell : System.Web.UI.Page
{
/// <summary>
/// There is a ButtonField column and the Id column
/// therefore first edit cell index is 2
/// </summary>
private const int _firstEditCellIndex = 2;
#region Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
_sampleData = null;
this.GridView1.DataSource = _sampleData;
this.GridView1.DataBind();
}
if (this.GridView1.SelectedIndex > -1)
{
// Call UpdateRow on every postback
this.GridView1.UpdateRow(this.GridView1.SelectedIndex, false);
}
}
#endregion
#region GridView1
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get the LinkButton control in the first cell
LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
// Get the javascript which is assigned to this LinkButton
string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");
// Add events to each editable cell
for (int columnIndex = _firstEditCellIndex; columnIndex < e.Row.Cells.Count; columnIndex++)
{
// Add the column index as the event argument parameter
string js = _jsSingle.Insert(_jsSingle.Length - 2, columnIndex.ToString());
// Add this javascript to the onclick Attribute of the cell
e.Row.Cells[columnIndex].Attributes["onclick"] = js;
// Add a cursor style to the cells
e.Row.Cells[columnIndex].Attributes["style"] += "cursor:pointer;cursor:hand;";
}
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView _gridView = (GridView)sender;
switch (e.CommandName)
{
case ("SingleClick"):
// Get the row index
int _rowIndex = int.Parse(e.CommandArgument.ToString());
// Parse the event argument (added in RowDataBound) to get the selected column index
int _columnIndex = int.Parse(Request.Form["__EVENTARGUMENT"]);
// Set the Gridview selected index
_gridView.SelectedIndex = _rowIndex;
// Bind the Gridview
_gridView.DataSource = _sampleData;
_gridView.DataBind();
// Write out a history if the event
this.Message.Text += "Single clicked GridView row at index " + _rowIndex.ToString()
+ " on column index " + _columnIndex + "<br />";
// Get the display control for the selected cell and make it invisible
Control _displayControl = _gridView.Rows[_rowIndex].Cells[_columnIndex].Controls[1];
_displayControl.Visible = false;
// Get the edit control for the selected cell and make it visible
Control _editControl = _gridView.Rows[_rowIndex].Cells[_columnIndex].Controls[3];
_editControl.Visible = true;
// Clear the attributes from the selected cell to remove the click event
_gridView.Rows[_rowIndex].Cells[_columnIndex].Attributes.Clear();
// Set focus on the selected edit control
ClientScript.RegisterStartupScript(GetType(), "SetFocus",
"<script>document.getElementById('" + _editControl.ClientID + "').focus();</script>");
// If the edit control is a dropdownlist set the
// SelectedValue to the value of the display control
if (_editControl is DropDownList && _displayControl is Label)
{
((DropDownList)_editControl).SelectedValue = ((Label)_displayControl).Text;
}
// If the edit control is a textbox then select the text
if (_editControl is TextBox)
{
((TextBox)_editControl).Attributes.Add("onfocus", "this.select()");
}
break;
}
}
/// <summary>
/// Update the sample data
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridView _gridView = (GridView)sender;
if (e.RowIndex > -1)
{
// Loop though the columns to find a cell in edit mode
for (int i = _firstEditCellIndex; i < _gridView.Columns.Count; i++)
{
// Get the editing control for the cell
Control _editControl = _gridView.Rows[e.RowIndex].Cells[i].Controls[3];
if (_editControl.Visible)
{
int _dataTableColumnIndex = i - 1;
try
{
// Get the id of the row
Label idLabel = (Label)_gridView.Rows[e.RowIndex].FindControl("IdLabel");
int id = int.Parse(idLabel.Text);
// Get the value of the edit control and update the DataTable
DataTable dt = _sampleData;
DataRow dr = dt.Rows.Find(id);
dr.BeginEdit();
if (_editControl is TextBox)
{
dr[_dataTableColumnIndex] = ((TextBox)_editControl).Text;
}
else if (_editControl is DropDownList)
{
dr[_dataTableColumnIndex] = ((DropDownList)_editControl).SelectedValue;
}
dr.EndEdit();
// Save the updated DataTable
_sampleData = dt;
// Clear the selected index to prevent
// another update on the next postback
_gridView.SelectedIndex = -1;
// Repopulate the GridView
_gridView.DataSource = dt;
_gridView.DataBind();
}
catch (ArgumentException)
{
this.Message.Text += "Error updating GridView row at index "
+ e.RowIndex + "<br />";
// Repopulate the GridView
_gridView.DataSource = _sampleData;
_gridView.DataBind();
}
}
}
}
}
protected void AddRow_Click(object sender, EventArgs e)
{
// Add a new empty row
DataTable dt = _sampleData;
int newid = dt.Rows.Count + 1;
dt.Rows.Add(new object[] { newid, "", "", "" });
_sampleData = dt;
// Repopulate the GridView
this.GridView1.DataSource = _sampleData;
this.GridView1.DataBind();
}
#endregion
#region Render Override
// Register the dynamically created client scripts
protected override void Render(HtmlTextWriter writer)
{
// The client events for GridView1 were created in GridView1_RowDataBound
foreach (GridViewRow r in GridView1.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
for (int columnIndex = _firstEditCellIndex; columnIndex < r.Cells.Count; columnIndex++)
{
Page.ClientScript.RegisterForEventValidation(r.UniqueID + "$ctl00", columnIndex.ToString());
}
}
}
base.Render(writer);
}
#endregion
#region Sample Data
/// <summary>
/// Property to manage data
/// </summary>
private DataTable _sampleData
{
get
{
DataTable dt = (DataTable)Session["TestData"];
if (dt == null)
{
// Create a DataTable and save it to session
dt = new DataTable();
dt.Columns.Add(new DataColumn("Id", typeof(int)));
dt.Columns.Add(new DataColumn("Description", typeof(string)));
dt.Columns.Add(new DataColumn("AssignedTo", typeof(string)));
dt.Columns.Add(new DataColumn("Status", typeof(string)));
dt.Rows.Add(new object[] { 1, "Create a new project", "Declan", "Complete" });
dt.Rows.Add(new object[] { 2, "Build a demo applcation", "Olive", "In Progress" });
dt.Rows.Add(new object[] { 3, "Test the demo applcation", "Peter", "Pending" });
dt.Rows.Add(new object[] { 4, "Deploy the demo applcation", "Andy", "Pending" });
dt.Rows.Add(new object[] { 5, "Support the demo applcation", "", "Pending" });
// Add the id column as a primary key
DataColumn[] keys = new DataColumn[1];
keys[0] = dt.Columns["id"];
dt.PrimaryKey = keys;
_sampleData = dt;
}
return dt;
}
set
{
Session["TestData"] = value;
}
}
#endregion
}
運作效果圖:
2、通路Session資料,并分頁和排序
這個例子是使用者使用Session中資料。另外,進行分頁和排序。滑鼠點選編輯GridView單元格。
關鍵代碼:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
GridView _gridView = (GridView)sender;
// Alternate the sort direction
string sortDirection = "ASC";
if (GridView1SortDirection == SortDirection.Ascending)
{
sortDirection = "ASC";
GridView1SortDirection = SortDirection.Descending;
}
else
{
sortDirection = "DESC";
GridView1SortDirection = SortDirection.Ascending;
}
// Set the SortExpression and SortDirection
DataView _sampleDataView = _sampleData.DefaultView;
_sampleDataView.Sort = e.SortExpression + " " + sortDirection;
// Repopulate the GridView
_gridView.DataSource = _sampleDataView;
_gridView.DataBind();
}
/// <summary>
/// Property to maintain Gridview sort direction in viewstate
/// </summary>
public SortDirection GridView1SortDirection
{
get
{
if (ViewState["GridView1SortDirection"] == null)
ViewState["GridView1SortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["GridView1SortDirection"];
}
set
{
ViewState["GridView1SortDirection"] = value;
}
}
運作效果圖:
3、通過SqlDataSource控件通路資料
這個例子是使用者通路SQL2005伺服器資料庫。這個資料是通過SqlDataSource控件通路。另外,還有分頁和排序。滑鼠點選編輯GridView單元格。
關鍵代碼:
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#DEDFDE" AutoGenerateColumns="False"
BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical" DataSourceID="SqlDataSource1" DataKeyNames="Id"
OnRowDataBound="GridView1_RowDataBound" OnRowCommand="GridView1_RowCommand" OnRowUpdating="GridView1_RowUpdating"
AllowSorting="True" AllowPaging="True" PageSize="4">
<Columns>
<asp:ButtonField Text="SingleClick" CommandName="SingleClick" Visible="False"/>
<asp:TemplateField HeaderText="Id" SortExpression="Id">
<ItemTemplate>
<asp:Label ID="IdLabel" runat="server" Text='<%# Eval("Id") %>'></asp:Label>
<asp:TextBox ID="Id" runat="server" Text='<%# Eval("Id") %>' Width="30px" visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Task" SortExpression="Description">
<ItemTemplate>
<asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
<asp:TextBox ID="Description" runat="server" Text='<%# Eval("Description") %>' Width="175px" visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Assigned To" SortExpression="AssignedTo">
<ItemTemplate>
<asp:Label ID="AssignedToLabel" runat="server" Text='<%# Eval("AssignedTo") %>'></asp:Label>
<asp:DropDownList ID="AssignedTo" runat="server" Visible="false" AutoPostBack="true">
<asp:ListItem></asp:ListItem>
<asp:ListItem>Andy</asp:ListItem>
<asp:ListItem>Betty</asp:ListItem>
<asp:ListItem>Conor</asp:ListItem>
<asp:ListItem>Declan</asp:ListItem>
<asp:ListItem>Eamon</asp:ListItem>
<asp:ListItem>Fergal</asp:ListItem>
<asp:ListItem>Gordon</asp:ListItem>
<asp:ListItem>Helen</asp:ListItem>
<asp:ListItem>Iris</asp:ListItem>
<asp:ListItem>John</asp:ListItem>
<asp:ListItem>Kevin</asp:ListItem>
<asp:ListItem>Lorna</asp:ListItem>
<asp:ListItem>Matt</asp:ListItem>
<asp:ListItem>Nora</asp:ListItem>
<asp:ListItem>Olive</asp:ListItem>
<asp:ListItem>Peter</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" SortExpression="Status">
<ItemTemplate>
<asp:Label ID="StatusLabel" runat="server" Text='<%# Eval("Status") %>'></asp:Label>
<asp:DropDownList ID="Status" runat="server" Visible="false" AutoPostBack="true">
<asp:ListItem>Pending</asp:ListItem>
<asp:ListItem>In Progress</asp:ListItem>
<asp:ListItem>Complete</asp:ListItem>
<asp:ListItem>Cancelled</asp:ListItem>
<asp:ListItem>Suspended</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#F7F7DE" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<FooterStyle BackColor="#6B696B" />
<PagerStyle BackColor="#6B696B" ForeColor="White" HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
<br /><br />
<asp:Label id="Message" runat="server" ForeColor="Red" Font-Bold="true"></asp:Label>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
DeleteCommand="DELETE FROM [Tasks] WHERE [Id] = @Id" InsertCommand="INSERT INTO [Tasks] ([Description], [AssignedTo], [Status]) VALUES (@Description, @AssignedTo, @Status)"
SelectCommand="SELECT * FROM [Tasks]" UpdateCommand="UPDATE [Tasks] SET [Description] = @Description, [AssignedTo] = @AssignedTo, [Status] = @Status WHERE [Id] = @Id" >
<DeleteParameters>
<asp:Parameter Name="Id" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="AssignedTo" Type="String" />
<asp:Parameter Name="Status" Type="String" />
<asp:Parameter Name="Id" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="AssignedTo" Type="String" />
<asp:Parameter Name="Status" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
運作效果圖:
4、通過ObjectDataSource控件通路資料
這個例子是使用者通路SQL2005伺服器資料庫。這個資料是通過ObjectDataSource控件通路。另外,還有分頁和排序。滑鼠點選編輯GridView單元格。
關鍵代碼:
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
SelectMethod="GetTasks" TypeName="TaskDataAccess"
UpdateMethod="UpdateTask" SortParameterName="sortExpression">
<UpdateParameters>
<asp:Parameter Name="id" Type="Int32" />
<asp:Parameter Name="description" Type="String" />
<asp:Parameter Name="assignedTo" Type="String" />
<asp:Parameter Name="status" Type="String" />
</UpdateParameters>
</asp:ObjectDataSource>
運作效果圖:
5、GridView使用Excel樣式通路Session資料
這個例子是使用者使用Session中資料。滑鼠點選編輯GridView單元格。
關鍵代碼:
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical"
OnRowDataBound="GridView1_RowDataBound" OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="False" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:ButtonField Text="SingleClick" CommandName="SingleClick" Visible="False"/>
<asp:ButtonField Text="DoubleClick" CommandName="DoubleClick" Visible="False"/>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="RowLabelsLabel" runat="server" Text='<%# Eval("Id") %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" CssClass="ssRowLabel" />
</asp:TemplateField>
<asp:TemplateField HeaderText="A">
<ItemTemplate>
<asp:Label ID="ALabel" runat="server" Text='<%# Eval("A") %>'></asp:Label>
<asp:TextBox ID="A" runat="server" Text='<%# Eval("A") %>' visible="false" CssClass="ssTextBox"></asp:TextBox>
</ItemTemplate>
<ItemStyle CssClass="ssCell" />
</asp:TemplateField>
<asp:TemplateField HeaderText="B">
<ItemTemplate>
<asp:Label ID="BLabel" runat="server" Text='<%# Eval("B") %>'></asp:Label>
<asp:TextBox ID="B" runat="server" Text='<%# Eval("B") %>' visible="false" CssClass="ssTextBox"></asp:TextBox>
</ItemTemplate>
<ItemStyle CssClass="ssCell" />
</asp:TemplateField>
<asp:TemplateField HeaderText="C">
<ItemTemplate>
<asp:Label ID="CLabel" runat="server" Text='<%# Eval("C") %>'></asp:Label>
<asp:TextBox ID="C" runat="server" Text='<%# Eval("C") %>' visible="false" CssClass="ssTextBox"></asp:TextBox>
</ItemTemplate>
<ItemStyle CssClass="ssCell" />
</asp:TemplateField>
<asp:TemplateField HeaderText="D">
<ItemTemplate>
<asp:Label ID="DLabel" runat="server" Text='<%# Eval("D") %>'></asp:Label>
<asp:TextBox ID="D" runat="server" Text='<%# Eval("D") %>' visible="false" CssClass="ssTextBox"></asp:TextBox>
</ItemTemplate>
<ItemStyle CssClass="ssCell" />
</asp:TemplateField>
<asp:TemplateField HeaderText="E">
<ItemTemplate>
<asp:Label ID="ELabel" runat="server" Text='<%# Eval("E") %>'></asp:Label>
<asp:TextBox ID="E" runat="server" Text='<%# Eval("E") %>' visible="false" CssClass="ssTextBox"></asp:TextBox>
</ItemTemplate>
<ItemStyle CssClass="ssCell" />
</asp:TemplateField>
<asp:TemplateField HeaderText="F">
<ItemTemplate>
<asp:Label ID="FLabel" runat="server" Text='<%# Eval("F") %>'></asp:Label>
<asp:TextBox ID="F" runat="server" Text='<%# Eval("F") %>' visible="false" CssClass="ssTextBox"></asp:TextBox>
</ItemTemplate>
<ItemStyle CssClass="ssCell" />
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="ssHeader" />
</asp:GridView>
運作效果圖:
6、GridView使用Excel樣式通過SqlDataSource控件通路資料
這個例子是使用者通路SQL2005伺服器資料庫。這個資料是通過SqlDataSource控件通路。滑鼠點選編輯GridView單元格。
關鍵代碼:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Spreadsheet]" DeleteCommand="DELETE FROM [Spreadsheet] WHERE [Id] = @Id" InsertCommand="INSERT INTO [Spreadsheet] ([A], [B], [C], [D], [E], [F]) VALUES (@A, @B, @C, @D, @E, @F)" UpdateCommand="UPDATE [Spreadsheet] SET [A] = @A, [B] = @B, [C] = @C, [D] = @D, [E] = @E, [F] = @F WHERE [Id] = @Id" >
<DeleteParameters>
<asp:Parameter Name="Id" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="A" Type="String" />
<asp:Parameter Name="B" Type="String" />
<asp:Parameter Name="C" Type="String" />
<asp:Parameter Name="D" Type="String" />
<asp:Parameter Name="E" Type="String" />
<asp:Parameter Name="F" Type="String" />
<asp:Parameter Name="Id" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="A" Type="String" />
<asp:Parameter Name="B" Type="String" />
<asp:Parameter Name="C" Type="String" />
<asp:Parameter Name="D" Type="String" />
<asp:Parameter Name="E" Type="String" />
<asp:Parameter Name="F" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
運作效果圖:
示範源代碼下載下傳位址:http://download.csdn.net/detail/lovegonghui/9264275