分享

c#常用编程方法

 thy 2009-04-03

1.将字符串NoList以','作为标记转换为字符串数组,用string[] arrList=NoList.Split(',')
2.关掉打开的当前窗口:
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能够进行页面之间的传值
 如test1.aspx的页面类中付值Session["DirectoryName"] = aa[0].ToString();当页面有test1.aspx跳转到test2.aspx后在test2.cs中可以通过这样的方法取值
 if(Session[DirectoryName]!=Null)
 {
  string temp=Session[DirectoryName];
 }
7.另外一种页面间传值的方法是在test1.cs中 this.Response.Redirect("test2.aspx?id=6");
 然后再test2.cs中通过这样的方法来取得该id
if (this.Request.QueryString["id"] == null)
 {
   string ID=this.Request.QueryString["AutoNo"].ToString().Trim();
}6,7两种方法在编程中会经常用到的
8. 在同一个页面之间不同函数间传值时ViewState的用处也很大
  付值:ViewState["OperationType"]=1;
  调用:
   if (ViewState["OperationType"] != null)
      {
         return Convert.ToString(ViewState["OperationType"]);
      }
9.对于用户从界面输入的信息,要注意进行字符校验,然后进行程序处理
一般采用这种方式
if (!this.CheckInput())
        {
           //处理过程
        }
10.类型转换:int.Parse  Convert.ToString()  Convert.ToDateTime等等
11.编写程序时注意随时在不太好理解的地方加上注释,对一些常用的函数要做成公用的函数以便调用
12.为界面按钮添加事件
 this.BtnDel.Attributes.Add("onclick","return confirm('确认删除?')");
13.有时候希望数据直接绑定到调用时定义的表dtTable,则采用out来进行数据回传,调用函数:GetDataTableFromID(id,out dtTable)
   被调用函数:GetDataTableFromID(int id, out DataTable drReturn)
14.设置字符串形式如果data1为string型,data2位int型,data3为DateTime型,则按如下方式来写
string.Format("输出的三个数字为:'{0}',{1},'{2}'",data1,data2,data3),后面的数据data1,data2,data3将会代替{}中的内容输出。
15.设置一个实体类的属性:
 private int m_intAutoID;
public int AutoID
{
  get
 {
   return m_intAutoID;
 }
  set
 {
  m_intAutoID=value;
 }
}
16.ArrayList的使用方法:
ArrayList 是一种动态数组,下面给出一个简单的例子:
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.获得一个随机数:
   string temp;
   temp=new Random().Next(10000,99999).ToString();
19.在html界面定义一个javascript函数,然后在服务器端调用该函数
  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.一般在后台弹出提示框的写法: Response.write(<script>alert("请重先输入密码!")</script>)
   也可以专门做一个提示函数放到公用方法中,然后在前台进行调用就可以了
   函数:  (假设这个函数在Share类中)
   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, "联系人手机号不能为空!");
21. 用javascript脚本输出界面的一个单元格,其中有小时,分钟的选择的两个下拉选择框
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>时间:</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>点</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.在服务器后台写script脚本,打开一个新页面
   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="时 间">
                    <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="信息类别">
                    <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绑定的数据源后,会自动在界面上绑定出Title字段的数据
对于Text='<%# htTypeId[Eval("HotLineTypeID")] %>'则需要在后台程序中添加这样的程序
public Hashtable htTypeId
    {

        get
        {

            if (ViewState["htTypeId"] != null)
            {

                return (Hashtable)ViewState["htTypeId"];
            }
            else
            {

                return null;
            }
        }
        set
        {

            ViewState["htTypeId"] = value;
        }
    }
将返回的值进行绑定
24.关于用户控件
   在页面中重复出现较多的模块,我们可以把它做成用户控件,比如网站的头尾模块。这样我们在每个页面需要添加头尾模块时只需要
 将这个控件拖入网页中即可,用户控件以.ascx结尾。
25.自定义控件,对于一些功能模块,如果使用频繁,我们也可以把它做成一个控件,比如日期控件(在论坛上已提供下载)需要使用时直接从面板中拖入即可,一般是建一个类库,
调试完成后,编译成.dll文件,在工具箱中点击选择项,将该dll文件添加进取,就可以像普通TextBox一样去使用它了。
26.前台用脚本编写dropDownList的onchange事件,后台编写控件的触发脚本
 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中如何对其所绑定的模版列数据进行操作
 前台:<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这个Label进行处理
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..等等进行判断,但是为了增强程序的易读性,需要使用enum将其所代表的意思表达出来,
可以单独做一个类来实现这个功能
如:
  namespace enumDemo
  {
    public enum RightEnum
 {
   //组,用户,角色维护
   GroupEdit=1,
   //功能项维护
   FunctionEdit=2,
   //权限点维护
   RightEdit=3,
 }
  }
引用时,直接用RightEnum.GroupEdit即代表1,这样会使程序更清晰。
29.弹出页返回时对上级页界面控件的编程
   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:撤销
   F5:启动调试
   F10:单步调试,不进入下级函数体
   F11:单步调试,进入下级函数体
   F7: 页面和后台代码页的切换
   F1:帮助
32.获取服务器上虚拟应用程序根路径: Context.Request.ApplicationPath
   例如在web项目test下有一个Default1.aspx和一个Default2.aspx页面
   则从Default1.aspx跳转到Default2.aspx的代码为:
   Response.Redirect(Context.Request.ApplicationPath+"Default2.aspx");
33.一个实用的加密函数
     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.一个解密字符串:
   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, "&!#-?,:*");
   采用这种方法可以把加密后的字符串保存到数据库中,即使有人看到数据库也是一个加密后的字符串,增强了系统的安全性。
36.HTML页面中引用.css文件
     <LINK href="../css/main.css" type="text/css" rel="stylesheet">
     注意"../"的写法如果要引用css的页面为A页面,则../表示A页面的上一级目录
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.判断一个字符串是否属于另一个字符串一部分
   string temp="chinese";
   int flag=temp.IndexOf("ese")
   则 flag=4 ("ese"字符串在temp中的位置)
   如果 int flag=temp.IndexOf("iceworld");
   则 flag=-1("iceworld"不属于temp字符串的一部分)
39.获取与服务器上虚拟路径相对应的物理文件路径
   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.再编程中可能会出现错误,不同的错误提示的信息不同,有些很难懂,我们可以在一个类中专门对一些常见的错误进行处理。
   如在ExceptionHandler类中定义这个的函数
   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行没有数据!";
    }
    }
   }
   这样在程序中为了方便读取异常信息,可以这样写
   string result=semiManage.Update();
   Response.Write("<script>alert('"+ExceptionHandler.DealErrorMsg(result)+"')</script>");
41.对于一些公用的函数,我们可以也单独建一个类进行集中处理
   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这个命名空间
42.为了系统安全,用户长时间不使用系统以致session过期时,需要重先登陆才能继续使用系统
   可以让每个页面继承一个基类BasicPage,基类中进行如下编码
   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.在类的组织中,如果有些类有公用的一些方法,可以抽象出一个基类,让其它类都继承这个基类,也可以再为基类定义一个接口,
便于实现多重继承;简单介绍一下一种多重继承方法。
A基类--A接口--A类
A基类--B接口--B类
AB类: A基类,A接口,B接口
注意在AB类的构造函数中需要实例化A,B两个类,则可以调用AB中的方法。
44.验证一个TextBox(例如名字为txtName)为必须输入或者限定其某种输入格式的方法
添加一个RegularExpressionValidator,然后指定其ControlToValidate的属性为txtName,
ErrorMessage显示如果输入出错时提示的信息;validationExpression属性如果不填,将对输入是否为空进行校验;
如果输入一个正则表达式,则如果输入格式有误,会提示错误信息。
45.对用户输入的字符串进行加密
 string password=FormsAuthentication.HashPasswordForStoringInConfigFile(this.Password.Text,"MD5");
 其中 FormsAuthentication类属于System.Web.Security命名空间。
46.DataGrid中删除一条记录时,要实现立即刷新并且有相应删除提示(下边为Favorite.aspx页面的部分html代码)
   可以增加一个模版列
   <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>
然后在后台进行处理
if(Request.QueryString["type"].ToUpper() == "DEL")
this.DelFavorite();
在DelFavorite()函数中通过int Info_ID = Int32.Parse(this.operate.FormatString(Request.QueryString["Info_ID"].ToString()));
获取的ID就能够删除这一条记录并给出相应提示信息。
47.
Request.ServerVariables("Path_Info")
客户端提供的路径信息
Request.ServerVariables("Remote_Addr")
发出请求的远程主机的IP地址
Response.Redirect(Request.ServerVariables["PATH_INFO"]);
通过上面这种方式可以实现刷新本页面功能。
48.cs结构程序中的假进度条
   在主要处理函数开始处定义
   int roll=0;
   在主函数处理环节中
    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;
  }
 }
    这样主函数每执行两遍,会将进度条滚动一次,提示用户程序正在处理中。
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文件中写入数据
strData为需要写入的字符串
 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中输入字符超长时,Box长度随着字符长度而变化。
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(要匹配的字符串);
 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    来自: thy > 《c#》

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多