1.將字符串NoList以','作為標記轉換為字符串數組,用string[] arrList=NoList.Split(',')
2.關(guān)掉打開(kāi)的當前窗口:
public static void CloseWindow(Page page)
{
string strScript="<script language=\"JavaScript\" type=\"text/javascript\">\n"+
"window.close();\n"+
"</script>\n";
page.Response.Write(strScript);
}
3.判斷字符串是否為空:string.IsNullOrEmpty(this.str);
4.ViewState用法
if(ViewState["OperationType"]!=null)
{
return (string)ViewState["OperationType"];
}
5.this.Page.RegisterStartupScript("note","<script LANGUAGE = JScript>window.alert('保存成功!'); window.document.URL='Supervise.aspx';</script>");
6.Session能夠進(jìn)行頁(yè)面之間的傳值
如test1.aspx的頁(yè)面類(lèi)中付值Session["DirectoryName"] = aa[0].ToString();當頁(yè)面有test1.aspx跳轉到test2.aspx后在test2.cs中可以通過(guò)這樣的方法取值
if(Session[DirectoryName]!=Null)
{
string temp=Session[DirectoryName];
}
7.另外一種頁(yè)面間傳值的方法是在test1.cs中 this.Response.Redirect("test2.aspx?id=6");
然后再test2.cs中通過(guò)這樣的方法來(lái)取得該id
if (this.Request.QueryString["id"] == null)
{
string ID=this.Request.QueryString["AutoNo"].ToString().Trim();
}6,7兩種方法在編程中會(huì )經(jīng)常用到的
8. 在同一個(gè)頁(yè)面之間不同函數間傳值時(shí)ViewState的用處也很大
付值:ViewState["OperationType"]=1;
調用:
if (ViewState["OperationType"] != null)
{
return Convert.ToString(ViewState["OperationType"]);
}
9.對于用戶(hù)從界面輸入的信息,要注意進(jìn)行字符校驗,然后進(jìn)行程序處理
一般采用這種方式
if (!this.CheckInput())
{
//處理過(guò)程
}
10.類(lèi)型轉換:int.Parse Convert.ToString() Convert.ToDateTime等等
11.編寫(xiě)程序時(shí)注意隨時(shí)在不太好理解的地方加上注釋,對一些常用的函數要做成公用的函數以便調用
12.為界面按鈕添加事件
this.BtnDel.Attributes.Add("onclick","return confirm('確認刪除?')");
13.有時(shí)候希望數據直接綁定到調用時(shí)定義的表dtTable,則采用out來(lái)進(jìn)行數據回傳,調用函數:GetDataTableFromID(id,out dtTable)
被調用函數:GetDataTableFromID(int id, out DataTable drReturn)
14.設置字符串形式如果data1為string型,data2位int型,data3為DateTime型,則按如下方式來(lái)寫(xiě)
string.Format("輸出的三個(gè)數字為:'{0}',{1},'{2}'",data1,data2,data3),后面的數據data1,data2,data3將會(huì )代替{}中的內容輸出。
15.設置一個(gè)實(shí)體類(lèi)的屬性:
private int m_intAutoID;
public int AutoID
{
get
{
return m_intAutoID;
}
set
{
m_intAutoID=value;
}
}
16.ArrayList的使用方法:
ArrayList 是一種動(dòng)態(tài)數組,下面給出一個(gè)簡(jiǎn)單的例子:
ArrayList List=new ArrayList();
for(int i=0;i<10;i++)
List.Add(i);
List.RemoveAt(5);
for(int i=0;i<3;i++)
List.Add(i+20);
Int32[] values=(Int32[])List.ToArray(typeof(Int32));
17.GridView中隊LinkButton模版列的操作:
前臺界面
<asp:TemplateColumn HeaderText="操作">
<HeaderStyle HorizontalAlign="Center" Width="15%"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
<ItemTemplate>
<asp:LinkButton id="lnbView" CommandName="View" CausesValidation="False" Runat="server">查看</asp:LinkButton>
<asp:LinkButton id="lnbErase" CommandName="Erase" CausesValidation="False" Runat="server">刪除</asp:LinkButton>
</ItemTemplate>
</asp:TemplateColumn>
后臺代碼的處理部分
protected void drgDisplay_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
switch (e.CommandName)
{
case "View":
//處理部分
break;
case "Erase":
//處理部分
break;
}
}
18.獲得一個(gè)隨機數:
string temp;
temp=new Random().Next(10000,99999).ToString();
19.在html界面定義一個(gè)javascript函數,然后在服務(wù)器端調用該函數
html界面:
<script type="text/javascript" lanaguage="javascript">
function cwin(strDepart)
{
var a=strDepart;
var mikecatstr=window.ShowModalDialog('../../UserControl/UcSelectPerson.aspx',a,'dialogHeight:500px;dialogWidth:585px');
//處理部分
}
后臺調用代碼:
string a="343";
this.ImaBu.Attributes.Add("onclick","cwin("+a+")");
20.一般在后臺彈出提示框的寫(xiě)法: Response.write(<script>alert("請重先輸入密碼!")</script>)
也可以專(zhuān)門(mén)做一個(gè)提示函數放到公用方法中,然后在前臺進(jìn)行調用就可以了
函數: (假設這個(gè)函數在Share類(lèi)中)
public static void PromptMessage(Page page,string strMessage)
{
StringBuilder sb=new StringBuilder("<script language='javascript'> window.");
sb.Append("alert('");
sb.Append(StringUtility.HtmlMsgStringFormatFix(strMessage));
sb.Append("')");
sb.Append("</script>");
if(!page.ClientScript.IsClientScriptBlockRegistered("display"))
{
page.ClientScript.RegisterStartupScript(page.GetType(),"display",sb.ToString());
}
}
后臺程序調用
Share.PromptMessage(this.Page, "聯(lián)系人手機號不能為空!");
21. 用javascript腳本輸出界面的一個(gè)單元格,其中有小時(shí),分鐘的選擇的兩個(gè)下拉選擇框
tableDate = mainIFrame.document.createElement("TABLE");
_TR = tableDate.insertRow();
_TD = _TR.insertCell();
_TD.height = 1;
_TD.bgColor = "black";
_TR = tableDate.insertRow();
_TD = _TR.insertCell();
_TD.innerHTML="<table cellspacing=0 cellpadding=0 class=calendar style='border:0px solid;width:100%'>"
+"<tr><td width=60 align=center>時(shí)間:</td><td><select id=\"drophour\" onchange=\"return parent.ChangeHour(this);\" ><option>0</option><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option><option>8</option><option>9</option><option>10</option><option>11</option><option>12</option><option>13</option><option>14</option><option>15</option><option>16</option><option>17</option><option>18</option><option>19</option><option>20</option><option>21</option><option>22</option><option>23</option></select></td>"
+"<td>點(diǎn)</td>"
+"<td><select id=\"drophour\" onchange=\"return parent.ChangeMinute(this);\"><option>0</option><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option><option>8</option><option>9</option><option>10</option><option>11</option><option>12</option><option>13</option><option>14</option><option>15</option><option>16</option><option>17</option><option>18</option><option>19</option><option>20</option><option>21</option><option>22</option><option>23</option><option>24</option><option>25</option><option>26</option><option>27</option><option>28</option><option>29</option><option>30</option><option>31</option><option>32</option><option>33</option><option>34</option><option>35</option><option>36</option><option>37</option><option>38</option><option>39</option><option>40</option><option>41</option><option>42</option><option>43</option><option>44</option><option>45</option><option>46</option><option>47</option><option>48</option><option>49</option><option>50</option><option>51</option><option>52</option><option>53</option><option>54</option><option>55</option><option>56</option><option>57</option><option>58</option><option>59</option></select></td>"
+"<td width='150' align=left>分</td>"
+"</tr></table>";
22.在服務(wù)器后臺寫(xiě)script腳本,打開(kāi)一個(gè)新頁(yè)面
Share.OpenWindow(this,"ExportToExcel.aspx?DepartmentNo="+DepartNo)
在Share中的OpenWindow函數:
public static void OpenWindow(Page page,string strUrl)
{
string strScript;
strScript="<script language=javascript>";
strScript+="var intHeight=600;";
strScript+="var intWidth=window.screen.width-150;";
strScript+="var strFeature='height='+intHeight+',width='+intWidth+',left=80,toolbar=no,status=yes,menubar=yes,location=yes,resizable=yes,scrollbars=yes';";
strUrl="window.open('"+strUrl+"','_blank',strFeature,true);";
strScript+=strUrl;
strScript+="</script>";
if (!page.ClientScript.IsStartupScriptRegistered("windowOpen"))
page.ClientScript.RegisterStartupScript(page.GetType(), "windowOpen", strScript);
}
23.GridView的數據綁定
前臺html:
<asp:TemplateField HeaderText="標 題">
<ItemTemplate>
<asp:HyperLink ID="HyperLinkTitle" runat="server" Text='<%# Eval("Title") %>' CssClass="link3"></asp:HyperLink>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" Wrap="False" />
<HeaderStyle HorizontalAlign="Center" Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="時(shí) 間">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("AddTime","{0:yyyy-MM-dd HH:mm}") %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="120px" Wrap="False" />
<HeaderStyle HorizontalAlign="Center" Width="120px" Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="信息類(lèi)別">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# htTypeId[Eval("HotLineTypeID")] %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="100px" Wrap="False" />
<HeaderStyle HorizontalAlign="Center" Width="100px" Wrap="False" />
</asp:TemplateField>
對于Text='<%# Eval("Title")這種格式,當指定GridView綁定的數據源后,會(huì )自動(dòng)在界面上綁定出Title字段的數據
對于Text='<%# htTypeId[Eval("HotLineTypeID")] %>'則需要在后臺程序中添加這樣的程序
public Hashtable htTypeId
{
get
{
if (ViewState["htTypeId"] != null)
{
return (Hashtable)ViewState["htTypeId"];
}
else
{
return null;
}
}
set
{
ViewState["htTypeId"] = value;
}
}
將返回的值進(jìn)行綁定
24.關(guān)于用戶(hù)控件
在頁(yè)面中重復出現較多的模塊,我們可以把它做成用戶(hù)控件,比如網(wǎng)站的頭尾模塊。這樣我們在每個(gè)頁(yè)面需要添加頭尾模塊時(shí)只需要
將這個(gè)控件拖入網(wǎng)頁(yè)中即可,用戶(hù)控件以.ascx結尾。
25.自定義控件,對于一些功能模塊,如果使用頻繁,我們也可以把它做成一個(gè)控件,比如日期控件(在論壇上已提供下載)需要使用時(shí)直接從面板中拖入即可,一般是建一個(gè)類(lèi)庫,
調試完成后,編譯成.dll文件,在工具箱中點(diǎn)擊選擇項,將該dll文件添加進(jìn)取,就可以像普通TextBox一樣去使用它了。
26.前臺用腳本編寫(xiě)dropDownList的onchange事件,后臺編寫(xiě)控件的觸發(fā)腳本
drpType.Attributes.Add("onchange",changeType();");
前臺:
<script language="javascript">
function changeType()
{
if(document.all.drpYwlb.value!="")
{
if(document.all.drpYwlb.value!="Select")
{
eval("document.all.querycondition"+document.all.drpYwlb.value+".style.display=''")
}
}
else
{
for(iii=1;iii<5;iii++)
{
eval("document.all.querycondition"+iii+".style.display='none'");
}
}
}
27.GridView中如何對其所綁定的模版列數據進(jìn)行操作
前臺:<asp:TemplateField HeaderText="序號">
<ItemStyle HorizontalAlign="Center" Wrap="False" Width="40px" />
<ItemTemplate>
<asp:Label ID="lblIndex" runat="server">Label</asp:Label>
</ItemTemplate>
<HeaderStyle Width="40px" />
</asp:TemplateField>
咱們在后臺對lblIndex這個(gè)Label進(jìn)行處理
protected void gvPeople_RowDataBound(object sender,GridViewRowEventArg e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
Label lblIndex;
lblIndex=(Label)e.Row.Cell[1].FindControl("lblIndex");
lblIndex.Text=Convert.ToString(2);
}
}
28.有些數據字段在程序控制中一般以1,2,3,4..等等進(jìn)行判斷,但是為了增強程序的易讀性,需要使用enum將其所代表的意思表達出來(lái),
可以單獨做一個(gè)類(lèi)來(lái)實(shí)現這個(gè)功能
如:
namespace enumDemo
{
public enum RightEnum
{
//組,用戶(hù),角色維護
GroupEdit=1,
//功能項維護
FunctionEdit=2,
//權限點(diǎn)維護
RightEdit=3,
}
}
引用時(shí),直接用RightEnum.GroupEdit即代表1,這樣會(huì )使程序更清晰。
29.彈出頁(yè)返回時(shí)對上級頁(yè)界面控件的編程
dialogArguments.document.all.txtOriginRecord.value="none";
30.在單元格中檢索按鈕的onmouseover onmouseout事件的編程:
<TD align="right"><INPUT class="smbuttonStyle" id="Submit1" onmouseover="blackFont(this)";" onmouseout="whiteFont(this);"
type="submit" value="檢索" name="submitb" runat="server" ></TD>
腳本程序:
function blackFont(param){
var blackVar = '#000000';
try
{
if(!document.layers){
param.style.color=blackVar;
}
}
catch(e)
{}
}
31.幾種常用的快捷鍵
Ctrl+A:全選
Ctrl+S:保存
Ctrl+F:查找
Ctrl+Z:撤銷(xiāo)
F5:啟動(dòng)調試
F10:單步調試,不進(jìn)入下級函數體
F11:單步調試,進(jìn)入下級函數體
F7: 頁(yè)面和后臺代碼頁(yè)的切換
F1:幫助
32.獲取服務(wù)器上虛擬應用程序根路徑: Context.Request.ApplicationPath
例如在web項目test下有一個(gè)Default1.aspx和一個(gè)Default2.aspx頁(yè)面
則從Default1.aspx跳轉到Default2.aspx的代碼為:
Response.Redirect(Context.Request.ApplicationPath+"Default2.aspx");
33.一個(gè)實(shí)用的加密函數
public static string Encrypt(string pToEncrypt, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//把字符串放到byte數組中
byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
//建立加密對象的密鑰和偏移量
//原文使用ASCIIEncoding.ASCII方法的GetBytes方法
//使得輸入密碼必須輸入英文文本
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
//Write the byte array into the crypto stream
//(It will end up in the memory stream)
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
//Get the data back from the memory stream, and into a string
StringBuilder ret = new StringBuilder();
foreach(byte b in ms.ToArray())
{
//Format as hex
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();
}
34.一個(gè)解密字符串:
public static string Decrypt(string pToDecrypt, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//Put the input string into the byte array
byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for(int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
//建立加密對象的密鑰和偏移量,此值重要,不能修改
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
//Flush the data through the crypto stream into the memory stream
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
//Get the decrypted data back from the memory stream
//建立StringBuild對象,CreateDecrypt使用的是流對象,必須把解密后的文本變成流對象
StringBuilder ret = new StringBuilder();
return System.Text.Encoding.Default.GetString(ms.ToArray());
}
35.程序中加密調用:Person.PerPwd = Security.Encrypt(this.PerPwd.Text, "&!#-?,:*");
采用這種方法可以把加密后的字符串保存到數據庫中,即使有人看到數據庫也是一個(gè)加密后的字符串,增強了系統的安全性。
36.HTML頁(yè)面中引用.css文件
<LINK href="../css/main.css" type="text/css" rel="stylesheet">
注意"../"的寫(xiě)法如果要引用css的頁(yè)面為A頁(yè)面,則../表示A頁(yè)面的上一級目錄
37.StringBuilder的用法
StringBuilder sb=new StringBuilder();
sb.Append("1=1");
if(this.SearchValue.Text!="")
{
sb.AppendFormat("and {0} like '%{1}%'",this.SearchType.SelectedValue,this.SearchValue.Text);
}
38.判斷一個(gè)字符串是否屬于另一個(gè)字符串一部分
string temp="chinese";
int flag=temp.IndexOf("ese")
則 flag=4 ("ese"字符串在temp中的位置)
如果 int flag=temp.IndexOf("iceworld");
則 flag=-1("iceworld"不屬于temp字符串的一部分)
39.獲取與服務(wù)器上虛擬路徑相對應的物理文件路徑
string s1=DateTime.Now.ToString("yyyyMM"); (200612)
string s2=DateTime.Now.ToString("dd"); (29)
path=Server.MapPath("/book/upload/"+s1+"/"+s2);
if(!Directory.Exists(path))
{
DirectoryInfo di=Directory.CreateDirectory(path);
}
40.再編程中可能會(huì )出現錯誤,不同的錯誤提示的信息不同,有些很難懂,我們可以在一個(gè)類(lèi)中專(zhuān)門(mén)對一些常見(jiàn)的錯誤進(jìn)行處理。
如在ExceptionHandler類(lèi)中定義這個(gè)的函數
pullic static string DealError(string errmsg)
{
if(errmsg.IndexOf(Index was outside the bounds of the array.">=0)
{
return "數組超界,請檢查!";
else if( errmsg.IndexOf("There is no row at position 0")>=0)
{
return "第0行沒(méi)有數據!";
}
}
}
這樣在程序中為了方便讀取異常信息,可以這樣寫(xiě)
string result=semiManage.Update();
Response.Write("<script>alert('"+ExceptionHandler.DealErrorMsg(result)+"')</script>");
41.對于一些公用的函數,我們可以也單獨建一個(gè)類(lèi)進(jìn)行集中處理
1.安全轉換字符串為數字
public static decimal ConvertToNum(object obj)
{
try
{
return Convert.ToDecimal(obj);
}
catch
{
return 0;
}
}
2.格式化數字
public static string FormatDecimal(string NumString)
{
try
{
decimal tempvalue=Convert.ToDecimal(NumString);
return tempvlue.ToString("0.####");
}
catch
{
return "";
}
}
3.格式化日期
public static string FormatDate(string DateString)
{
try
{
DateTime tempvalue=Convert.ToDateTime(DateString);
return tempvalue.ToString("yyyy-MM-dd");
}
catch
{
return "";
}
}
4.格式化字符串函數
public string FormatString(string str)
{
if(str!=null)
{
str=str.Trim();
str=str.Replace("'","’")
str=str.Replace("|","");
}
return str;
}
5.檢查字符串是否是合法數字
public static bool IsNumber(string NumString)
{
return Regex.IsMatch(NumString,"^\\d+(?:\\.\\d+)?$");
}
其中Regex屬于System.Text.RegularExpressions這個(gè)命名空間
42.為了系統安全,用戶(hù)長(cháng)時(shí)間不使用系統以致session過(guò)期時(shí),需要重先登陸才能繼續使用系統
可以讓每個(gè)頁(yè)面繼承一個(gè)基類(lèi)BasicPage,基類(lèi)中進(jìn)行如下編碼
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.Load+=new System.EventHandle(this.MainPage_Load);
}
private void MainPage_Load(object sender,System.EventArgs e)
{
if(Context.User.Identity.IsAuthenticated)
{
}
else
{
Response.Redirect("~/Login.aspx");
}
}
43.在類(lèi)的組織中,如果有些類(lèi)有公用的一些方法,可以抽象出一個(gè)基類(lèi),讓其它類(lèi)都繼承這個(gè)基類(lèi),也可以再為基類(lèi)定義一個(gè)接口,
便于實(shí)現多重繼承;簡(jiǎn)單介紹一下一種多重繼承方法。
A基類(lèi)--A接口--A類(lèi)
A基類(lèi)--B接口--B類(lèi)
AB類(lèi): A基類(lèi),A接口,B接口
注意在A(yíng)B類(lèi)的構造函數中需要實(shí)例化A,B兩個(gè)類(lèi),則可以調用AB中的方法。
44.驗證一個(gè)TextBox(例如名字為txtName)為必須輸入或者限定其某種輸入格式的方法
添加一個(gè)RegularExpressionValidator,然后指定其ControlToValidate的屬性為txtName,
ErrorMessage顯示如果輸入出錯時(shí)提示的信息;validationExpression屬性如果不填,將對輸入是否為空進(jìn)行校驗;
如果輸入一個(gè)正則表達式,則如果輸入格式有誤,會(huì )提示錯誤信息。
45.對用戶(hù)輸入的字符串進(jìn)行加密
string password=FormsAuthentication.HashPasswordForStoringInConfigFile(this.Password.Text,"MD5");
其中 FormsAuthentication類(lèi)屬于System.Web.Security命名空間。
46.DataGrid中刪除一條記錄時(shí),要實(shí)現立即刷新并且有相應刪除提示(下邊為Favorite.aspx頁(yè)面的部分html代碼)
可以增加一個(gè)模版列
<asp:TemplateColumn HeaderText="修改">
<ItemStyle HorizontalAlign="Center"></ItemStyle>
<ItemTemplate>
<asp:HyperLink NavigateUrl='<%# "/Company/Chance/Favorite.aspx?type=DEL&Info_ID="+DataBinder.Eval(Container.DataItem,"Info_ID") %>' Runat="server" ID="Hyperlink1">
刪除
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateColumn>
然后在后臺進(jìn)行處理
if(Request.QueryString["type"].ToUpper() == "DEL")
this.DelFavorite();
在DelFavorite()函數中通過(guò)int Info_ID = Int32.Parse(this.operate.FormatString(Request.QueryString["Info_ID"].ToString()));
獲取的ID就能夠刪除這一條記錄并給出相應提示信息。
47.
Request.ServerVariables("Path_Info")
客戶(hù)端提供的路徑信息
Request.ServerVariables("Remote_Addr")
發(fā)出請求的遠程主機的IP地址
Response.Redirect(Request.ServerVariables["PATH_INFO"]);
通過(guò)上面這種方式可以實(shí)現刷新本頁(yè)面功能。
48.cs結構程序中的假進(jìn)度條
在主要處理函數開(kāi)始處定義
int roll=0;
在主函數處理環(huán)節中
if(roll%2==0)
{
this.ProgressBar(5000);
}
結尾處
roll++;
if(roll==100)
{
roll=0;
}
private void ProgressBar(int count)
{
progressBar.Value=1;
progressBar.Minimum=1;
progressBar.Maximum=count;
for(int step=1;step<count;step++)
{
progressBar.Value =step;
}
}
這樣主函數每執行兩遍,會(huì )將進(jìn)度條滾動(dòng)一次,提示用戶(hù)程序正在處理中。
49.從xml中取出相應信息(bak.config)
<?xml version="1.0"?>
<ProjectConnection>
<Project name="源數據庫" select="true" remark="">
<BasiceData>server=10.210.5.184;database=cgHott;uid=cghot;pwd=5656;Pooling=true;Max Pool Size=10;Min Pool Size=0;Connection Lifetime=300;packet size=1000</BasiceData>
<BasiceData>server=10.210.5.154;database=cgHott;uid=cghot;pwd=565;Pooling=true;Max Pool Size=10;Min Pool Size=0;Connection Lifetime=300;packet size=1000</BasiceData>
</Project>
</ProjectConnection>
后臺cs代碼
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load("bak.config");
System.Xml.XmlNode root = doc.DocumentElement;
System.Xml.XmlNode target = root.SelectSingleNode("descendant::Project[@name='源數據庫']");
strChecked = target.Attributes["select"].Value;
string strCon=target.ChildNodes[0].InnerXml;
則能夠取到 strCon="10.210.5.184;database=cgHott;uid=cghot;pwd=5656;Pooling=true;Max Pool Size=10;Min Pool Size=0;Connection Lifetime=300;packet size=1000"
50.向xml文件中寫(xiě)入數據
strData為需要寫(xiě)入的字符串
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load("bak.config");
System.Xml.XmlNode root = doc.DocumentElement;
System.Xml.XmlNode target = root.SelectSingleNode("descendant::Project[@name='源數據庫']");
if( target != null )
{
target.ChildNodes[0].InnerXml = strData;
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter("bak.config",null);
writer.Formatting = System.Xml.Formatting.Indented;
doc.Save(writer);
writer.Close();
}
51.在程序里面調用web.config里面的SQL server連接字段
<appSettings>
<add key="wjcking"
value="SQL 連接字段"/>
</appSettings>
調用:
string sql_connection_string=System.Configuration.ConfigurationSettings.AppSettings["wjcking"];
52.
string currentLine = ...;
string[] items = currentLine.Split(new string[] { ", " }, StringSplitOptions.None);
53.
ComBox中輸入字符超長(cháng)時(shí),Box長(cháng)度隨著(zhù)字符長(cháng)度而變化。
private void findWidthForDropDown(ComboBox comboBox)
{
bool isDatabound = comboBox.DataSource != null && comboBox.DisplayMember != null && comboBox.DisplayMember != "";
int widestWidth = comboBox.DropDownWidth;
string valueToMeasure;
int currentWidth;
using (Graphics g = comboBox.CreateGraphics())
{
for (int i = 0; i < comboBox.Items.Count; i++)
{
if (isDatabound)
valueToMeasure = (string)((DataRowView)comboBox.Items[i])[comboBox.DisplayMember];
else
valueToMeasure = comboBox.Items[i].ToString();
currentWidth = (int)g.MeasureString(valueToMeasure, comboBox.Font).Width;
if (currentWidth > widestWidth) { widestWidth = currentWidth; }
}
}
comboBox.DropDownWidth = widestWidth;
}
54.數組的定義
int[] array = new int[10]; // 整型一維數組
for (int i = 0; i < array.Length; i++)
array[i] = i;
or int[] test = new int[] { 1, 3, 4 };
int[,] array2 = new int[5,10]; // 整型二維數組
array2[1,2] = 5;
55.用正則表達式匹配
using System.Text.RegularExpressions;
Regex regex = new System.Text.RegularExpressions.Regex(正則);
regex.IsMatch(要匹配的字符串);
聯(lián)系客服