zoukankan      html  css  js  c++  java
  • Visual C#程序设计技巧汇集

    在网上看到不少技巧,不禁想把他们整理好放上来,顺便加入自己编程的时候学习到的技巧。

    以下技巧是转发http://soft.yesky.com/SoftChannel/72342380468109312/20041117/1876614.shtml
    获取文件的版本信息:

    FileVersionInfo myFileVersionInfo1 = FileVersionInfo.GetVersionInfo("D:\\TEST.DLL");
    textBox1.Text="版本号: " + myFileVersionInfo1.FileVersion;

      更改文件属性,删除只读文件:

      下例欲将E:\test.txt文件拷贝至D:\tmp\test.txt,但D:\tmp\test.txt已经存在。

    //File.Copy(sourceFile,destinationFile,true); 用来拷贝文件
    //当destinationFile已经存在时,无法将文件file1拷贝到目标文件,
    //因此先删除destination文件,File.Delete()方法不能删除只读文件,
    //因此,如果文件属性为只读(Attributes属性中会包含有"ReadOnly"),
    //先把文件属性重置为Normal,然后再删除:
    string file1="E:\\test.txt";
    string destinationFile="d:\\tmp\\test.txt";
    if(File.Exists(destinationFile))
    {
     FileInfo fi=new FileInfo(destinationFile);
     if(fi.Attributes.ToString().IndexOf("ReadOnly")!=-1)
      fi.Attributes=FileAttributes.Normal;
      File.Delete(destinationFile);
    }
    File.Copy(file1,destinationFile,true);

      C#中字符串的格式化及转换成数值的方法

      字符串转换成数字,比如"1234"转换成数字1234:

    string str="1234";
    int i=Convert.ToInt32(str);

      格式化字符串,向长度小于30的字符串末尾添加特定字符,补足n个字符,使用String类的PadRight(int,char)方法:

    String str="1234";
    str=str.PadRight(30,' ') //向长度小于30的字符串末尾添加空格,补足30个字符

      按行读写文件

      判断文件是否存在:File.Exists(string filePath)

      判断目录是否存在:Directory.Exists("D:\\LastestVersion")

      按行读取文件:

    int fileCount=0;
    // Open the file just specified such that no one else can use it.
    StreamReader sr = new StreamReader(textBox1.Text.Trim());
    while(sr.Peek() > -1)//StreamReader.Peek()返回下一个可用字符,但不使用它
    {
     listBox1.Items.Add(sr.ReadLine());
     fileCount++;
    }
    sr.Close();

      按行写入文件:

    StreamWriter sw = new StreamWriter("D:\\result.txt");
    for(int i=0;i<10;i++)
    {
     sw.WriteLine("这是第"+i.ToString()+"行数据");
    }

      文件目录对话框的使用

      文件对话框即过滤条件的使用:

    string resultFile="";
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.InitialDirectory = "D:\\Patch" ;
    openFileDialog1.Filter = "All files (*.*)|*.*|txt files (*.txt)|*.txt" ;
    openFileDialog1.FilterIndex = 2 ;
    openFileDialog1.RestoreDirectory = true ;
    if(openFileDialog1.ShowDialog() == DialogResult.OK)
    resultFile=openFileDialog1.FileName;

      目录对话框的使用:

    string resultFolder="";
    FolderBrowserDialog openFolderDialog1=new FolderBrowserDialog();
    openFolderDialog1.RootFolder=Environment.SpecialFolder.MyComputer;
    if(openFolderDialog1.ShowDialog()==DialogResult.OK)
    resultFolder=openFolderDialog1.SelectedPath;

    1. ~ 的用法

      一般的情况下,我们是使用./../ 这样的相对路径来确定和规划我们的资源(比如图片、资源文件),但这种方式下在我们部署应用的时候,可能会出错,另外对于.ascx的控件中如果包含了一个图片,而这个控件被我们在不同层次的两个目录的aspx文件分别引用时,问题就会出现了。

      ~/image/about.bmp 是一种非常好的方法,它以Web应用程序的根目录为起始点,这样使得比你使用./image/about.bmp这样的方式要更加灵活和方便。有一点不好,是这种方式是在ASP.NET运行时动态解析的,所以在IDE设计模式中,你可能不能预览它。

    2. 在刷新和提交页面后,保存你的页面滚动条的位置

      经常有这样的情况,我们需要用户提交一个表单,但是表单中有超过500+个?控件或文本框要填写,也就是说用户需要拉动IE的滚动条才能够填得完,那么假如用户正在可见IE范围的2/3处,选择了一个组合框的值,很不幸组合框是服务器端的,那么也就意味着页面会提交一次,而当用户再看见刷新过的页面时,页面确定在3/1的地方也就是显示在页面最开始的地方,用户只有拖动鼠标,然后接着刚刚的地方再填写剩下的250个控件,很不幸,370个控件又需要他选择一下?

      用下面的方法可以很快地确定和记住你提交前的位置。

      网上的Old Dog Learns New Tricks也有一个类似的例子Maintain Scroll Position in any Page Element,不过他使用了Web Behavior这意味着你需要使用一个.htc文件

    Private Sub RetainScrollPosition()

    Dim saveScrollPosition As New StringBuilder
    Dim setScrollPosition As New StringBuilder

    RegisterHiddenField("__SCROLLPOS", "0")
    saveScrollPosition.Append("<script language='javascript'>")
    saveScrollPosition.Append("function saveScrollPosition() {")
    saveScrollPosition.Append(" document.forms[0].__SCROLLPOS.value = thebody.scrollTop;")
    saveScrollPosition.Append("}")
    saveScrollPosition.Append("thebody.onscroll=saveScrollPosition;")
    saveScrollPosition.Append("</script>")

    RegisterStartupScript("saveScroll", saveScrollPosition.ToString())

    If (Page.IsPostBack = True) Then

    setScrollPosition.Append("<script language='javascript'>")
    setScrollPosition.Append("function setScrollPosition() {")
    setScrollPosition.Append(" thebody.scrollTop = " & Request("__SCROLLPOS") & ";")
    setScrollPosition.Append("}")
    setScrollPosition.Append("thebody.onload=setScrollPosition;")
    setScrollPosition.Append("</script>")
    RegisterStartupScript("setScroll", setScrollPosition.ToString())

    End If

    End Sub

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    RetainScrollPosition()
    End Sub


    3. DataList使用不同风格的模板

      这招也非常实用,你可以制作两个不同的模板或表现形式,分别以.ascx控件的形式保存,运行时根据某个条件动态的选择使用其中的一个模板,另外ScottGu认为ItemDataBound方法也可以定制你显示的表现,比如加亮某个元素或是加一个促销广告图等等。

    Dim theme As String
    theme = DropDownList1.SelectedValue

    DataList1.ItemTemplate = Page.LoadTemplate(theme & ".ascx") ---Cool
    DataList1.DataSource = DS
    DataList1.DataBind()

      4. 设置服务器端控件的焦点

    Private Sub SetFocus(ByVal controlToFocus As Control)
    Dim scriptFunction As New StringBuilder
    Dim scriptClientId As String

    scriptClientId = controlToFocus.ClientID
    scriptFunction.Append("<script language='javascript'>")
    scriptFunction.Append("document.getElementById('" & scriptClientId & "').focus();")
    scriptFunction.Append("</script>")
    RegisterStartupScript("focus", scriptFunction.ToString())
    End Sub

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    If (Page.IsPostBack = False) Then
    SetFocus(TextBox1)
    End If
    End Sub

      5. 滚动DataGrid

      这招就更简单了,有时候你的页面只有一个固定的地方,但是需要显示非常多的数据,亦或是也不定,但是只有固定的一个地方给你显示它了。这时你就可以用下面这招,自动出滚动条,而且适用许多控件。很简单将你的控件放在一个DIV中将overflow属性设置成auto

    <div style=“height:400px;200px;overflow:auto”>
    <asp:datagrid id=“MyGrid” runat=“server”/>
    </div>

      6. 动态创建控件

      利用PlaceHolder控件,这东西在ASP.NET 2.0 Mutil-View和Master Page中运用的就更加多了。

    Sub Page_Load()
    Dim i as Integer
    For i=0 to 4
    Dim myUserControl as Control
    myUserControl = Page.LoadControl(“foo.ascx”)
    PlaceHolder1.Controls.Add(myUserControl)
    PlaceHolder1.Controls.Add(New LiteralControl(“<br>”))
    Next i
    End Sub

      7. 客户端代码的使用

      1). 可以使用客户端的事件代码,但两者不能同名,服务器端代码的名是你可以控制的。对于非ASP.NET的标准控件的自定义控件必须实现IAttributeAccessor接口或从WebControl派生并且可用expando属性

    asp:ImageButton id=“foo”
    ImageUrl=“start.jpg”
    onMouseOver=“rollover(this);”
    onMouseOut=“rollout(this)”
    rolloversrc=“myrollover.jpg”
    rolloutsrc=“myrollout.jpg”
    runat=“server”/>

    <input type=Button onClick=“return clientHandler()”
    onServerClick=“Button1_Click” … />

      2). 使用可以在Postback之前执行客户端代码,当然也可以取消这次Postback,另外也可以访问客户端该页所有的客户端控件。

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)  Handles MyBase.Load
     RegisterOnSubmitStatement("foo", "return confirm('Are you sure you want to submit the order?');")
    End Sub

      3). 还有更复杂的我认为不实用,大家可以自己去看,主要是运用RegisterStartupScript和JavaScript的技术

      以上文章介绍了一些ASP.NET中常用而且比较实用的技巧,希望能对大家的实际开发有所裨益!

  • 相关阅读:
    线程唤醒
    以前、现在
    黑马程序员训练营基础测试
    流程图
    线程同步
    Thread联系
    Java线程
    Java中文件流笔记
    字符串习题
    匿名内部类
  • 原文地址:https://www.cnblogs.com/dagon007/p/149164.html
Copyright © 2011-2022 走看看