⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 datagrideditproducts.aspx

📁 asp.net技术内幕的书配源码
💻 ASPX
字号:
<%@ Page Language="C#" debug="true"%>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat=server>
SqlConnection conNorthwind = new SqlConnection( @"Server=localhost;Integrated Security=SSPI;Database=Northwind" );
string strSql;  
  
void Page_Load(Object sender , EventArgs e)
{
	if (! IsPostBack )
		BindDataGrid();
}

void BindDataGrid()
{
	SqlCommand cmdSql = new SqlCommand( "Select * From Products", conNorthwind );
	conNorthwind.Open();
	dgrdProducts.DataSource = cmdSql.ExecuteReader();
	dgrdProducts.DataBind();
	conNorthwind.Close();
}

void dgrdProducts_EditCommand( Object sender, DataGridCommandEventArgs e )
{
	dgrdProducts.EditItemIndex = e.Item.ItemIndex;
	BindDataGrid();
}

void dgrdProducts_UpdateCommand( Object sender, DataGridCommandEventArgs e )
{
	int intProductID;
	string strProduct;
	string strProductName;
	decimal decUnitPrice;
	intProductID = (int)dgrdProducts.DataKeys[e.Item.ItemIndex];
	  
	TextBox txtProductName = (TextBox)e.Item.Cells[1].Controls[0];

	TextBox txtUnitPrice = (TextBox)e.Item.Cells[2].Controls[0];

	strProductName = txtProductName.Text;
	decUnitPrice = Decimal.Parse(txtUnitPrice.Text.Remove(0,1));
	strSql = "Update Products Set ProductName=@ProductName, " + "UnitPrice=@UnitPrice Where ProductID=@ProductID";
	SqlCommand cmdSql = new SqlCommand( strSql, conNorthwind );
	cmdSql.Parameters.Add( "@ProductName", strProductName );
	cmdSql.Parameters.Add( "@UnitPrice", decUnitPrice );
	cmdSql.Parameters.Add( "@ProductID", intProductID );
	conNorthwind.Open();
	cmdSql.ExecuteNonQuery();
	conNorthwind.Close();
	dgrdProducts.EditItemIndex = -1;
	BindDataGrid();
}

void dgrdProducts_CancelCommand(Object sender, DataGridCommandEventArgs e )
{
	dgrdProducts.EditItemIndex = -1;
	BindDataGrid();
}
</Script>

<html>
<head><title>DataGridEditProducts.aspx</title></head>
<body>
<form Runat="Server">

<asp:DataGrid
  ID="dgrdProducts"
  OnEditCommand="dgrdProducts_EditCommand"
  OnUpdateCommand="dgrdProducts_UpdateCommand"
  OnCancelCommand="dgrdProducts_CancelCommand"
  DataKeyField="ProductID"
  AutoGenerateColumns="False"
  CellPadding="10"
  HeaderStyle-BackColor="Salmon"
  Runat="Server">
<Columns>
  <asp:BoundColumn
    HeaderText="Product ID"
    DataField="ProductID"
    ReadOnly="True" />
  <asp:BoundColumn
    HeaderText="Product Name"
    DataField="ProductName" />
  <asp:BoundColumn
    HeaderText="Price"
    DataField="UnitPrice"
    DataFormatString="{0:c}" />
  <asp:EditCommandColumn
    EditText="Edit!"
    UpdateText="Update!"
    CancelText="Cancel!" />
</Columns>
</asp:DataGrid>

</form>
</body>
</html>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -