直播中
<Columns>
<asp:EditCommandColumn ButtonType="LinkButton" UpdateText= "<img border=0 src=ok.gif>" CancelText= "<imgborder=0 src=cancel.gif>" EditText= "<imgborder=0src=edit.gif>"></asp:EditCommandColumn>
<asp:ButtonColumn Text= "<img border= 0src= delete.gif>"CommandName="Delete"></asp:ButtonColumn>
<asp:BoundColumn DataField= "ProductID" SortExpression="ProductID" ReadOnly="True" HeaderText= "ProductID"></asp:BoundColumn>
<asp:BoundColumn DataField= "ProductName" SortExpression="ProductName" HeaderText= "ProductName"></asp:BoundColumn>
<asp:BoundColumn DataField="QuantityPerUnit" SortExpression="QuantityPerUnit" HeaderText= "Quantity PerUnit"></asp:BoundColumn>
<asp:BoundColumn DataField="UnitPrice" SortExpression="UnitPrice" HeaderText= "Unit Price"DataFormatString="{0:c}"></asp:BoundColumn>
<asp:BoundColumn DataField="UnitsInStock" SortExpression="UnitsInStock" HeaderText= "Units InStock"></asp:BoundColumn>
<asp:BoundColumn DataField="UnitsOnOrder" SortExpression="UnitsOnOrder" HeaderText= "Units OnOrder"></asp:BoundColumn>
<asp:BoundColumn DataField= "ReorderLevel" SortExpression="ReorderLevel" HeaderText= "ReorderLevel"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="Discontinued" SortExpression="Discontinued">
<ItemTemplate>
<asp:CheckBox id= "Discontinued" runat="server" Checked= '<%# DataBinder.Eval(Container.DataItem, "Discontinued")%>' />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
你看,是不是不難?關(guān)鍵在于我們常動手動腦。多看資料也很關(guān)鍵哦!
C#后臺程序:
讓我們先看一段程序:
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}
上面展現(xiàn)的是一種非常好的技術(shù),當(dāng)頁面不是PostBack狀態(tài)時,就綁定數(shù)據(jù)。這意味著,一旦頁面被請求數(shù)據(jù)將被綁定。
繼續(xù)看程序:
/// <summary>
/// 這個函數(shù)返回關(guān)于產(chǎn)品細(xì)節(jié)的DataSet
/// </summary>
///<returns></returns>
private DataSet GetProductData()
{
///SQLStatement是一個SQL語句(string型的)
string SQLStatement="SELECT Products.ProductID, Products.ProductName, Products.QuantityPerUnit, Products.UnitPrice, "+
"Products.UnitsInStock, Products.UnitsOnOrder, Products.ReorderLevel, Products.Discontinued "+
"FROM Products"; :
///聲明 SqlConnection對象:myConnection
SqlConnection myConnection=new SqlConnection(@"server=(local)\NetSDK;”+
”database=NorthWind;uid=northwind;pwd=northwind;");
///聲明Command對象:myCommand
SqlDataAdapter myCommand = new SqlDataAdapter(SQLStatement,myConnection);
///設(shè)置Command命令的類型為Text類型
myCommand.SelectCommand.CommandType=CommandType.Text;
///創(chuàng)建DataSet對象實例
myDataSet = new DataSet();
///把從表Products返回的數(shù)據(jù)填充myData
myCommand.Fill(myDataSet, "Products");
///最后返回myDataSet對象
return myDataSet;
}
這段代碼執(zhí)行給定的SQL語句訪問數(shù)據(jù)庫,私有函數(shù)GetProductData返回一個包含數(shù)據(jù)記錄的DataSet。下一步,讓我們看如何編輯記錄:
/// <summary>
/// 這個函數(shù)只有當(dāng)用戶點(diǎn)擊Edit按鈕時才會被激活
/// </summary>
/// <paramname="sender"></param>
/// <paramname="E"></param>
protected void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs E)
{
///找出被選定項目的索引(ItemIndex),并且進(jìn)一步綁定數(shù)據(jù)
MyDataGrid.EditItemIndex = (int)E.Item.ItemIndex;
BindGrid();
}
通過上面代碼所附帶的注解大家也能明白MyDataGrid_Edit函數(shù)的功能:當(dāng)用戶點(diǎn)擊Edit按鈕時激活MyDataGrid_Edit函數(shù),并且程序找到所要編輯的記錄的索引,把該索引號分配給DataGrid的EditItemIndex屬性。
如果用戶點(diǎn)擊Cancel按鈕,將調(diào)用我們在上面的.aspx文件中提到的MyDataGrid_Cancel函數(shù),程序如果分配給DataGrid屬性 EditItemIndex的值為-1,就意味著用戶沒有選擇Edit,程序如下:
/// <summary>
/// 用戶點(diǎn)擊Cancel按鈕時激活MyDataGrid函數(shù)
/// </summary>
/// <paramname="sender"></param>
/// <paramname="E"></param>
protected void MyDataGrid_Cancel(Object sender, DataGridCommandEventArgs E)
{
MyDataGrid.EditItemIndex = -1;
BindGrid();
}
下面的代碼像我們展現(xiàn)了如何從DataGrid中刪除一條選中的記錄。我們知道Web控件DataGrid有一DataKeyField屬性,事實上它就包含了每條記錄的ProductID字段值。您一定會問如何通過DataKeyField屬性得到DataGrid中選中記錄的ProductID值呢?下面這段代碼會讓您釋然的:
-----
int ProductID =(int)MyDataGrid.DataKeys[(int)E.Item.ItemIndex];
-----
MyDataGrid_Delete函數(shù)代碼如下:
/// <summary>
///從DataSet中刪除一條記錄
/// </summary>
/// <param name="sender"></param>
/// <param name="E"></param>
protected void MyDataGrid_Delete(Object sender, DataGridCommandEventArgs E)
{
int ProductID =(int)MyDataGrid.DataKeys[(int)E.Item.ItemIndex];
string SQLStatement="Delete Products WHERE ProductID="+ProductID;
string myConnectionString = "server=localhost;uid=sa;pwd=;database=NorthWind";
SqlConnection myConnection = new SqlConnection(myConnectionString);
SqlCommand myCommand = new SqlCommand (SQLStatement,myConnection);
myCommand.CommandTimeout = 15;
myCommand.CommandType=CommandType.Text;
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
catch(Exception ee)
{
throw ee;
}
MyDataGrid.EditItemIndex = -1;
BindGrid();
}
下面的代碼用來更新NorthWind數(shù)據(jù)庫的產(chǎn)品信息,
我們可以使用下面這項技術(shù)檢索值:
-------------------
bool Discon=((CheckBox)E.Item.FindControl("Discontinued")).Checked;
-------------------
這時我們使用FinControl()方法就能得到Discontinued CheckBox的值.
/// <summary>
///更新記錄
/// </summary>
/// <param name="sender"></param>
/// <param name="E"></param>
protected void MyDataGrid_Update(Object sender, DataGridCommandEventArgs E)
{
int ProductID =(int)MyDataGrid.DataKeys[(int)E.Item.ItemIndex];
string ProductName = ((TextBox)E.Item.Cells[3].Controls[0]).Text;
string QuantityPerUnit=((TextBox)E.Item.Cells[4].Controls[0]).Text;
string UnitPrice = ((TextBox)E.Item.Cells[5].Controls[0]).Text;
Int16 UnitsInStock=Int16.Parse(((TextBox)E.Item.Cells[6].Controls[0]).Text);
Int16 UnitsOnOrder=Int16.Parse(((TextBox)E.Item.Cells[7].Controls[0]).Text);
Int16 ReorderLevel=Int16.Parse(((TextBox)E.Item.Cells[8].Controls[0]).Text);
bool Discon=((CheckBox)E.Item.FindControl("Discontinued")).Checked;
int result;
if(!Discon)
{
result=0;
}
else
{
result=1;
}
string SQLStatement="UPDATE Products "+
"SET ProductName='"+ProductName+"', "+
"QuantityPerUnit='"+QuantityPerUnit+"', "+
"UnitPrice ="+UnitPrice.Substring(UnitPrice.IndexOf("¥")+1)+", "+
"UnitsInStock ="+UnitsInStock+", "+
"UnitsOnOrder ="+UnitsOnOrder+", "+
"ReorderLevel ="+ReorderLevel+", "+
"Discontinued ="+result+
" WHERE ProductID ="+ProductID;
string myConnectionString = "server=localhost;uid=xjb;pwd=xjb;database=Northwind";
SqlConnection myConnection = new SqlConnection(myConnectionString);
SqlCommand myCommand = new SqlCommand(SQLStatement,myConnection);
myCommand.CommandTimeout = 15;
myCommand.CommandType = CommandType.Text;
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
catch(Exception ee)
{
throw ee ;
}
MyDataGrid.EditItemIndex = -1;
BindGrid();
}
接下來的BindGrid()調(diào)用私有函數(shù)GetProductData取得DataSet對象并綁定到DataGrid控件。
/// <summary>
/// 接受數(shù)據(jù)庫數(shù)據(jù)并再次綁定
/// </summary>
protected void BindGrid()
{
MyDataGrid.DataSource=GetProductData().Tables["Products"].DefaultView;
MyDataGrid.DataBind();
}
用戶在DataGrid中向前或向后移動時激活MyDataGrid_PageIndexChanged事件,因為DataGrid 不能自動的獲取新頁的索引號,所以我們只能手動取得索引號。
/// <summary>
/// 分頁操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void MyDataGrid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
MyDataGrid.CurrentPageIndex=e.NewPageIndex;
BindGrid();
}
用戶在任何時候想對數(shù)據(jù)分類時,就激活下面的Sort_Grid事件。例如,如果用戶點(diǎn)擊field headers,事件就將被激活,并且把數(shù)據(jù)分成我們想要的分類。 我們需要DataView對象去為e.SortExpression.ToString()方法分類,返回的是被點(diǎn)擊域標(biāo)題的分類。
/// <summary>
/// 分類
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Sort_Grid(Object sender, DataGridSortCommandEventArgs e)
{
DataView dv= new DataView(GetProductData().Tables["Products"]);
dv.Sort= e.SortExpression.ToString();
MyDataGrid.DataSource=dv;
MyDataGrid.DataBind();
}
執(zhí)行結(jié)果:
該程序在win2000+SqlServer2000+VS.NETBeta2環(huán)境下測試成功,程序執(zhí)行結(jié)果