ASP.Net3.5中包含了新的數據綁定控件--ListView,這是一個類似與repeater與gridvIEw結合的控件,可以實現添加,刪除功能,同時還可以像repeater一樣靈活的控制頁面的布局。該控件包含了很多新的模板,比如GroupTemplate等新增的模板,可以方便的分組顯示數據。詳細的大家可以去查MSDN文檔。
我一直認為學習數據綁定控件從最簡單的增刪改查開始,可以對該控件有較深刻的理解,這樣可以舉一反三,在進行綜合運用。今天這篇文章還是從最基本的數據操作開始,對ListVIEw有個感性的認識。
首先看一下程序運行的效果:
頁面源碼:
<ASP:ListView ID="ListView1" runat="server" OnSelectedIndexChanging="ListVIEw1_SelectedIndexChanging"
OnItemCommand="ListVIEw1_ItemCommand"
OnItemEditing="ListView1_ItemEditing" OnItemCanceling="ListVIEw1_ItemCanceling"
OnItemDataBound="ListView1_ItemDataBound" OnPagePropertiesChanging="ListView1_PagePropertIEsChanging"
OnItemInserting="ListView1_ItemInserting" OnItemUpdating="ListVIEw1_ItemUpdating"
OnSorting="ListView1_Sorting" EnableVIEwState="true"
InsertItemPosition="LastItem" onitemdeleting="ListVIEw1_ItemDeleting">
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></ASP:PlaceHolder>
<p>
<ASP:DataPager ID="MyPage" runat="server" PageSize="6">
<FIElds>
<ASP:NumericPagerFIEld ButtonCount="10" PreviousPageText="<-- " NextPageText="-->" />
<%...-- <ASP:NextPreviousPagerFIEld ButtonType="Button" ShowFirstPageButton="true" ShowLastPageButton="true"
ShowNextPageButton="true" ShowPreviousPageButton="true" />--%>
</FIElds>
&n </ASP:DataPager>
</p>
</LayoutTemplate>
<ItemTemplate>
<i>
<%...#Eval("SupplIErID")%></i>
<p>
<b>
<%...#Eval("CompanyName")%></b></p>
<p>
<%...#Eval("ContactName")%></p>
<p>
<%...#Eval("Address")%></p>
<p>
<%...#Eval("City")%></p>
<ASP:Button ID="btnEdit" runat="server" Text="Edit" CommandName="Edit" />
<ASP:Button ID="btnDelete" runat="server" Text="Delete" CommandName="Delete" />
<%...-- <asp:LinkButton ID="lbtnSort" runat="server" Text="Sort" CommandName="Sort" CommandArgument="CompanyName" ></ASP:LinkButton>--%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtMy" runat="server" Text=''<%#bind("SupplIErID") %>''></ASP:TextBox>
<asp:TextBox ID="TextBox1" runat="server" Text=''<%#bind("CompanyName") %>''></ASP:TextBox>
<asp:TextBox ID="TextBox2" runat="server" Text=''<%#bind("ContactName") %>''></ASP:TextBox>
<asp:TextBox ID="TextBox3" runat="server" Text=''<%#bind("Address") %>''></ASP:TextBox>
<asp:TextBox ID="TextBox4" runat="server" Text=''<%#bind("City") %>''></ASP:TextBox>
<ASP:Button ID="btnUpdate" runat="server" Text="Update" CommandName="Update" />
<ASP:Button ID="btnCancle" runat="server" Text="Cancle" CommandName="Cancel" />
</EditItemTemplate>
& <InsertItemTemplate>
<asp:TextBox ID="txtMy" runat="server" Text=''<%#bind("SupplIErID") %>''></ASP:TextBox>
<asp:TextBox ID="TextBox1" runat="server" Text=''<%#bind("CompanyName") %>''></ASP:TextBox>
<asp:TextBox ID="TextBox2" runat="server" Text=''<%#bind("ContactName") %>''></ASP:TextBox>
<asp:TextBox ID="TextBox3" runat="server" Text=''<%#bind("Address") %>''></ASP:TextBox>
<asp:TextBox ID="TextBox4" runat="server" Text=''<%#bind("City") %>''></ASP:TextBox>
<ASP:Button ID="btnUpdate" runat="server" Text="Insert" CommandName="Insert" />
<ASP:Button ID="btnCancle" runat="server" Text="Cancle" CommandName="Cancel" />
</InsertItemTemplate>
<ItemSeparatorTemplate>
<div >
</div>
</ItemSeparatorTemplate>
</ASP:ListVIEw>
這部分代碼中有個重要的部分就是通過<LayoutTemplate>模板來設置控件的樣式,布局,這也是新增的模板。在VS.Net2008的正式版本中,要正常運行頁面必須在該模板中加入一個名為itemPlaceholder的PlaceHolder控件。要不會出現如下異常:
An item placeholder must be specified on ListView ''ListVIEw1''. Specify an item placeholder by setting a control''s ID property to "itemPlaceholder".
<ItemTemplate>模板用來綁定顯示到頁面上的數據, <EditItemTemplate>用來顯示處於編輯狀態的時候顯示的數據,其他的可以以此類推。
與ListView還搭配的一起使用了新增的DataPager控件,這個主要是用於ListVIEw控件的分頁,是新增的分頁空也,可以方便,高效的進行分頁。
後台代碼:
string ConStr = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
...{
if (!IsPostBack)
...{
ViewState["SupplierID"] = "SupplIErID";
VIEwState["Direction"] = "DESC";
BindListVIEw();
}
}
private void BindListVIEw()
...{
string QueryCon = "SELECT SupplierID,CompanyName,ContactName,Address,City FROM SupplIErs";
SqlConnection NorthWindCon = new SqlConnection(ConStr);
SqlDataAdapter NorthWindDa = new SqlDataAdapter(QueryCon, ConStr);
DataSet Ds = new DataSet();
NorthWindDa.Fill(Ds, "SupplIErs");
ListView1.DataKeyNames = new string[] ...{ "SupplIErID" };
DataView Dv = Ds.Tables["Suppliers"].DefaultVIEw;
//排序表達式
string SortExpress = (string)ViewState["SupplierID"] + " " + (string)VIEwState["Direction"];
&nb Dv.Sort = SortExpress;
//綁定數據源
//ListView1.DataSource = Ds.Tables["SupplIErs"];
ListVIEw1.DataSource = Dv;
ListVIEw1.DataBind();
}
protected void ListView1_ItemEditing(object sender, ListVIEwEditEventArgs e)
...{
ListVIEw1.EditIndex = e.NewEditIndex;
BindListVIEw();
}
protected void ListView1_ItemDataBound(object sender, ListVIEwItemEventArgs e)
...{
if (e.Item.ItemType == ListVIEwItemType.DataItem)
...{
((Button)e.Item.FindControl("btnDelete")).Attributes["onclick"] = "if(!confirm(''你真的要刪除這條記錄麼?''))return false;";
}
}
protected void ListView1_ItemCanceling(object sender, ListVIEwCancelEventArgs e)
...{
//取消編輯
if (e.CancelMode == ListVIEwCancelMode.CancelingEdit)
...{
//e.Cancel = true;
ListVIEw1.EditIndex = -1;
BindListVIEw();
ShowMessage("取消編輯");
}
else if (e.CancelMode == ListVIEwCancelMode.CancelingInsert)
...{
//BindListVIEw();
return;
}
}
protected void ListView1_ItemInserting(object sender, ListVIEwInsertEventArgs e)
...{
((TextBox)ListVIEw1.InsertItem.FindControl("txtMy")).ReadOnly = true;
string CompanyName = Server.HtmlEncode(((TextBox)ListVIEw1.InsertItem.FindControl("TextBox1")).Text.ToString());
string ContactName = Server.HtmlEncode(((TextBox)ListVIEw1.InsertItem.FindControl("TextBox2")).Text.ToString());
string Address = Server.HtmlEncode(((TextBox)ListVIEw1.InsertItem.FindControl("TextBox3")).Text.ToString());
string City = Server.HtmlEncode(((TextBox)ListVIEw1.InsertItem.FindControl("TextBox4")).Text.ToString());
string InsertQuery = "INSERT INTO SupplIErs (CompanyName,ContactName,Address,City) VALUES (''" + CompanyName + "'',''" + ContactName + "'',''" + Address + "'',''" + City + "'')";
SqlConnection InsertCon = new SqlConnection(ConStr);
SqlCommand InsertCmd = new SqlCommand(InsertQuery, InsertCon);
try
...{
InsertCon.Open();
InsertCmd.ExecuteNonQuery();
BindListVIEw();
//將插入行顯示到最後
ListVIEw1.InsertItemPosition = InsertItemPosition.LastItem;
}
catch
...{
ShowMessage("插入新數據出錯,請重新輸入");
}
finally
...{
InsertCon.Dispose();
InsertCmd.Dispose();
}
}
protected void ListView1_ItemUpdating(object sender, ListVIEwUpdateEventArgs e)
...{
string KeyId = ListVIEw1.DataKeys[e.ItemIndex].Value.ToString();
//找到listvIEw改行的數據集合
string CompanyName = Server.HtmlEncode(((TextBox)ListVIEw1.Items[e.ItemIndex].FindControl("TextBox1")).Text.ToString());
string ContactName = Server.HtmlEncode(((TextBox)ListVIEw1.Items[e.ItemIndex].FindControl("TextBox2")).Text.ToString());
string Address = Server.HtmlEncode(((TextBox)ListVIEw1.Items[e.ItemIndex].FindControl("TextBox3")).Text.ToString());
string City = Server.HtmlEncode(((TextBox)ListVIEw1.Items[e.ItemIndex].FindControl("TextBox4")).Text.ToString());
string UpdateStr = "UPDATE SupplIErs SET CompanyName=''" + CompanyName + "'',ContactName=''" + ContactName + "''," +
"Address=''" + Address + "'',City=''" + City + " ''WHERE SupplIErID=''" + KeyId + "'' ";
SqlConnection UpdateCon = new SqlConnection(ConStr);
SqlCommand UpdateCmd = new SqlCommand(UpdateStr, UpdateCon);
try
...{
UpdateCon.Open();
UpdateCmd.ExecuteNonQuery();
ListVIEw1.EditIndex = -1;
BindListVIEw();
}
catch
...{
ShowMessage("更新出錯,請重新編輯");
}
finally
...{
UpdateCon.Dispose();
UpdateCmd.Dispose();
}
}
protected void ListView1_Sorting(object sender, ListVIEwSortEventArgs e)
...{
if (ViewState["SupplIErID"].ToString() == e.SortExpression)
...{
if (VIEwState["Direction"].ToString() == "DESC")
...{
VIEwState["Direction"] = "ASC";
}
else
...{
VIEwState["Direction"] = "DESC";
}
}
else
...{
ViewState["SupplIErID"] = e.SortExpression;
}
BindListVIEw();
}
private void ShowMessage(string Message)
...{
Literal TxtMsg = new Literal();
TxtMsg.Text = "<script>alert(''" + Message + "'')</script>";
Page.Controls.Add(TxtMsg);
}
protected void ListView1_ItemDeleting(object sender, ListVIEwDeleteEventArgs e)
...{
string KeyID = ListVIEw1.DataKeys[e.ItemIndex].Value.ToString();
string DeleteStr = "DELETE FROM Suppliers WHERE SupplIErID=''" + KeyID + "''";
SqlConnection DeleteCon = new SqlConnection(ConStr);
SqlCommand DeleteCmd = new SqlCommand(DeleteStr, DeleteCon);
try
...{
DeleteCon.Open();
DeleteCmd.ExecuteNonQuery();
BindListVIEw();
ShowMessage("刪除成功");
}
catch
...{
ShowMessage("刪除出錯,請檢查數據是否有關聯");
}
finally
...{
DeleteCon.Dispose();
DeleteCmd.Dispose();
}
}
以前的edit_cancel事件在ListView控件中為item_cancel,在該事件中可以判斷是取消編輯還是取消插入新的數據。大家可以看代碼。本篇文章主要是對ListVIEw控件一些基本的事件的運用。下一篇會繼續深入的學習該控件。