程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> 一天精通asp.net的學習經驗小結

一天精通asp.net的學習經驗小結

編輯:ASP.NET基礎
1、Validator
2、IsPostBack
3、AutoPostBack。控件離開焦點的時候自動Post。
4、repeater控件的使用。:Repeater控件比以前版本的asp.net好用了,只要 Eval就可以了,不用DataBinder.Eval(container.DataItem,"***"):了,只要Eval("Name")就可以,注意不能丟了前面的“#”。
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
嘎嘎嘎
</HeaderTemplate>
<ItemTemplate>
<%# Eval("Name")%>
<%# Eval("Desc")%>
</ItemTemplate>
</asp:Repeater>

protected void Button3_Click(object sender, EventArgs e)
{
List<Person> list = new List<Person>();
list.Add(new Person(){Name="芭芭拉",Desc="白牙呗"});
list.Add(new Person(){Name="奧巴馬",Desc="黑黝黑"});
Repeater1.DataSource = list;
Repeater1.DataBind();
}
5、DataList控件:
(1)行的高亮選中
<asp:DataList ID="DataList1" runat="server" >
<SelectedItemStyle BackColor="#FF6666" />
<ItemTemplate>
<%# Eval("Name")%>
<%# Eval("Desc")%>
<asp:LinkButton ID="LinkButton1" runat="server" Text="選擇" CommandName="select" />
</ItemTemplate>
</asp:DataList>
核心是CommandName這個屬性,可選值還有edit、delete等可選值,當按鈕被點擊的時候將會執行EditCommand、DeleteCommand等事件。
(2)行的在位編輯:
<asp:DataList ID="DataList1" runat="server"
oneditcommand="DataList1_EditCommand">
<SelectedItemStyle BackColor="#FF6666" />
<EditItemTemplate>
<asp:TextBox runat="server" ID="t1" Text='<%# Eval("Name")%>' />
<asp:TextBox runat="server" ID="t2" Text='<%# Eval("Desc")%>' />
<asp:Button runat="server" Text="提交" CommandName="update" />
</EditItemTemplate>
<ItemTemplate>
<%# Eval("Name")%>
<%# Eval("Desc")%>
<asp:LinkButton ID="LinkButton1" runat="server" Text="編輯" CommandName="edit" />
</ItemTemplate>
</asp:DataList>

protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
{
DataList1.EditItemIndex = e.Item.ItemIndex;
ReBind();
}

private void ReBind()
{
List<Person> list = new List<Person>();
list.Add(new Person() { Name = "芭芭拉", Desc = "白牙呗" });
list.Add(new Person() { Name = "奧巴馬", Desc = "黑黝黑" });
Repeater1.DataSource = list;
Repeater1.DataBind();

DataList1.DataSource = list;
DataList1.DataBind();
}
(3)行的在位編輯並且提交修改
<asp:DataList ID="DataList1" runat="server"
oneditcommand="DataList1_EditCommand"
onupdatecommand="DataList1_UpdateCommand">
<SelectedItemStyle BackColor="#FF6666" />
<EditItemTemplate>
<asp:TextBox runat="server" ID="t1" Text='<%# Eval("Name")%>' />
<asp:TextBox runat="server" ID="t2" Text='<%# Eval("Desc")%>' />
<asp:Button runat="server" Text="提交" CommandName="update" />
</EditItemTemplate>
<ItemTemplate>
<%# Eval("Name")%>
<%# Eval("Desc")%>
<asp:LinkButton ID="LinkButton1" runat="server" Text="編輯" CommandName="edit" />
</ItemTemplate>
</asp:DataList>
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["PersonList"] == null)
{
List<Person> list = new List<Person>();
list.Add(new Person() { Name = "芭芭拉", Desc = "白牙呗" });
list.Add(new Person() { Name = "奧巴馬", Desc = "黑黝黑" });
Repeater1.DataSource = list;
Repeater1.DataBind();
Session["PersonList"] = list;
}
}

protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
{
DataList1.EditItemIndex = e.Item.ItemIndex;
ReBind();
}

private void ReBind()
{
DataList1.DataSource = Session["PersonList"];
DataList1.DataBind();
}

protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
{
TextBox nT1 = e.Item.FindControl("t1") as TextBox;
TextBox nT2 = e.Item.FindControl("t2") as TextBox;
//不要直接從DataList1.DataSource中取,因為取到的是null
List<Person> list = Session["PersonList"] as List<Person>;
Person curPerson = list[DataList1.EditItemIndex];
curPerson.Name = nT1.Text;
curPerson.Desc = nT2.Text;
DataList1.EditItemIndex = -1;
ReBind();
}
}
6 GridView控件
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False" onrowcommand="GridView1_RowCommand"
onsorting="GridView1_Sorting">
<Columns>
<asp:ButtonField ButtonType="Button" CommandName="DingGou" HeaderText="訂購"
ShowHeader="True" Text="訂購" />
<asp:ButtonField ButtonType="Button" CommandName="TuiDing" HeaderText="退訂"
ShowHeader="True" Text="退訂" />
<asp:BoundField DataField="Name" HeaderText="名稱" SortExpression="Name" />
<asp:BoundField DataField="Desc" HeaderText="描述" SortExpression="Desc" />
</Columns>
</asp:GridView>

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DingGou")
{
Debug.WriteLine("第"+e.CommandArgument+"行被訂購");
}
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{

}
7、用戶控件(UserControl)
通過向導創建一個UserControl,然後就可以任意編輯這個UserControl,而且還可以為UserControl增加屬性、事件。使用的時候只要將控件直接從SolutionExplorer拖到頁面上就可以。
8、繼承控件
(1)通過向導創建一個WebCustomControl。
(2)定義自己應用界面。需要重載從Control類繼承來的CreateChildControls方法,並在其中生成界面控件。如果用戶定義的控件會在一個頁面中反復使用,最好implements System.Web.UI.INamingContainer,它會為該控件創建一個唯一的命名空間。
(3)定義自己控件的消息處理函數。自己定義的控件含有兩種類型的消息,一是包含的子控件所產生的消息,二是自定義的控件消息。
9、向工程中添加“Global Application Class”就可以添加Global.asax,在這裡可以監聽Application、Session的生命周期。
10、(1)Response.Redirect("newpage.aspx");客戶端轉發
(2)Server.Transfer("newpage.aspx");服務器端轉發
11、web.config配置
(1) <appSettings>
<add key="FTP" value="127.0.0.1"/>
</appSettings>
this.Title = WebConfigurationManager.AppSettings["FTP"];
(2)
<connectionStrings>
<add name="mydb" connectionString="jdbc:ddd"/>
</connectionStrings>
this.Title = WebConfigurationManager.ConnectionStrings["mydb"].ConnectionString;
12、BulletedList就是<ul><ol>
13、PostBack本質論
ASP.NET also adds two additional hidden input fields that are used to pass information
back to the server. This information consists of the ID of the control that raised the event and
any additional information that might be relevant. These fields are initially empty, as shown
here:
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
The __doPostBack() function has the responsibility for setting these values with the
appropriate information about the event and then submitting the form. A slightly simplified
version of the __doPostBack() function is shown here:
<script language="text/javascript">
function __doPostBack(eventTarget, eventArgument) {
var theform = document.Form1;
theform.__EVENTTARGET.value = eventTarget;
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
</script>
14、跨頁表單提交
在頁1中指定按鈕的PostBackUrl屬性為WebForm1.aspx,這樣表單就會提交到WebForm1.aspx了,然後在WebForm1.aspx中還可以取到前一頁中所有的值:
TextBox1.Text = PreviousPage.Title;
還可以將PreviousPage cast成更詳細的頁面子類。
15、取QueryString的方法:
Request.QueryString["recordID"]
16、Server.UrlEncode(lstItems.SelectedItem.Text)
17、Multiview控件用來實現動態界面,Multiview裡嵌套多個view控件,每個view控件裡可以方式其他控件。通過控制Multiview控件的ActiveViewIndex屬性來控制不同View的顯示。
18、Wizard控件比Multiview控件更方面,更像一個TabControl
19、動態圖片:
在pageload的事件中:
Bitmap image = new Bitmap(300, 50);
Graphics g = Graphics.FromImage(image);
Response.ContentType = "image/png";
image.Save(Response.OutputStream,
System.Drawing.Imaging.ImageFormat.Gif);
20 頁面導航
創建SiteMap文件,修改SiteMap文件增加節點。
在頁面上增加一個SiteMapDataSource,然後只要拖TreeView、Menu、SiteMapPath等控件上來,指定DataSource屬性為SiteMapDataSource就可以了。
21 單值綁定
URL = "Images/picture.jpg";
this.DataBind();
<asp:CheckBox id="chkDynamic" Text="<%# URL %>" runat="server" />
22 下拉列表框綁定
<asp:DropDownList ID="DropDownList1" runat="server" DataTextField="value"
DataValueField="key">
</asp:DropDownList>
IDictionary<string, string> dict = new Dictionary<string, string>();
dict["1"] = "aa";
dict["2"] = "bb";
DropDownList1.DataSource = dict;
DropDownList1.DataBind();
23 設定起始頁:在aspx上點右鍵,選擇“Set as startpage”
24 程序中數據庫連接字符串的設置
(1)、web.config中加入:
<connectionStrings>
<add name="DBConnectionString" connectionString="server=192.168.88.128\SQLEXPRESS1;uid=sa;pwd=123456;database=CRM" providerName="System.Data.SqlClient"/>
</connectionStrings>
(2)、在IDE中拖放DataSource組件以後,在屬性視圖的ConnectionString屬性中選擇DBConnectionString即可。
(3)、程序中讀取這個連接字符串的方法:
System.Configuration.Configuration rootWebConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
string connString =
rootWebConfig.ConnectionStrings.ConnectionStrings["DBConnectionString"].ConnectionString;
24 制作簡單的CRUD頁面的步驟:
(1)拖放一個SqlDataSource組件上來,設定好ConnectionString,命名組件為dsList。
(2)修改SqlDataSource組件的DeleteQuery屬性為:delete from T_PSI_User where FId=@FId
InsertQuery屬性為:INSERT INTO T_PSI_User(FId, FUserName, FPassword) VALUES (NEWID(),@FUserName,@FPassword)
SelectQuery為:select * from T_PSI_User
UpdateQuery為:Update T_PSI_User set FUserName=@FUserName,FPassword=@FPassword where FId=@FId
(3)拖放一個GridView組件上來,設定其DataSourceID屬性為dsList。修改AllowPaging、AllowSorting、AutoGenerateDeleteButton、AutoGenerateEditButton屬性為True。設定AutoGeneratedColumns屬性為false。設定DataKeyNames屬性為FId(這樣哪怕隱藏了FId字段,Edit、delete功能也能正常執行了)
(4)修改GridView的Columns屬性,在彈出的對話框中點擊【RefreshSchema】鏈接,這樣在BoundField下就顯示了FId、FName、FPassword三個字段,將FUserName和FPassword字段Add進來。
這樣不用一行代碼,有刪、改功能的頁面就做好了。下面來做“增”的功能。
(5)選擇GridView組件,在智能提示中選擇EditTemplete、然後選擇“EmptyTemplete”,拖放一個FormView組件到EmptyTemplete中,選中Formview組件,在智能提示中設定DataSource為dsList。
(6)新建一個【新增】按鈕,編輯其Click事件代碼為:
GridView1.DataSourceID = "";
GridView1.DataBind();
(7)設定FormView的ItemInserted事件代碼為:
RefreshList();
RefreshList()函數定義如下:
GridView1.DataSourceID = "dsList";
GridView1.DataBind();
這樣“增”的功能就做好了,不過還是有缺憾,那就是顯示出了不歸我們管的FId字段,並且字段名、按鈕都是英文的。
(8)選中,FormView組件,然後點擊EditTemplete,選中InsertTemplete,這樣就可以刪除不需要的FId字段了,並且可以修改控件布局以及界面的語言文字。
(9)這樣的話Insert界面中的“Cancel取消”按鈕還是不能用,編輯FormView1的ItemCommand事件,編寫如下的代碼:
if (e.CommandName == "Cancel")
{
RefreshList();
}
25 上面實現CRUD的方法有兩個缺陷:
(1)需要編寫一個EmptyTemplete
(2)很難對Edit的控件做定制
因此我們還是用ListUI和EditUI分置的方法來解決。步驟:
制作ListUI:
(1)使用datasource、GridView,不過DataSource只要配置SelectQuery、DeleteQuery即可。
(2)GridView不自動生成Edit按鈕。
(3)GridView生成一個ButtonField,標題為“編輯”,CommandName="EditInPage"
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditInPage")
{
int index = Convert.ToInt32(e.CommandArgument);
Guid guid = (Guid)GridView1.DataKeys[index].Value;
Server.Transfer("/Sys/SysUserEdit.aspx?Action=Edit&FId="+guid);
}
}
(4)新增按鈕的Onclick事件:
Server.Transfer("/Sys/SysUserEdit.aspx?Action=Insert");

制作EditUI:
(1)拖一個DataSouce控件,按常規配置InsertCommand和UpdateCommand,配置SelectCommand為“SELECT * FROM [T_PSI_User] where 1<>1”,配置UpdateCommand為“”
(2)拖一個FormView上來,並且修改EditTemplete和InsertTemplte(可以直接將EditTemplete修改後的拷貝到InsertTemplte,注意不要忘了修改Button的CommandName)
(3)代碼;
protected void Page_Load(object sender, EventArgs e)
{
switch (Request["Action"])
{
case "Edit":
dsEdit.SelectCommand = "select * from T_PSI_User where FId=@FId";
dsEdit.SelectParameters.Clear();
dsEdit.SelectParameters.Add("FId", Request["FId"]);
FormView1.ChangeMode(FormViewMode.Edit);
break;
case "Insert":
FormView1.ChangeMode(FormViewMode.Insert);
break;
}
}

protected void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e)
{
GogoList();
}

protected void FormView1_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
{
GogoList();
}

private void GogoList()
{
Server.Transfer("/Sys/SysUserList.aspx");
}
}
}
26、DropDownList實現基礎資料選擇器,比如在商品編輯中的選擇計量單位:
(1)拖一個針對T_MeasureUnit表的DataSource,比如名字為dsMeasureUnit。
(2)拖一個商品的Datasource,比如dsMerchan。
(3)拖一個FormView上來,並且設定其DataSource為dsMerchan
(4)將一個DropDownList放到FormView中,因為只有這樣才能設定DropDownList本身的綁定。
(5)選中DropDownList,在智能提示中選擇“ConfigDateSource”,在這裡配置上dsMeasureUnit。
(6)選中DropDownList,在智能提示中選擇“EditDataBindings”,然後設定綁定到dsMerchan的FMeasureUnitId字段。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved