The Perfect Day

分享技术,编写未来

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  66 随笔 :: 0 文章 :: 10 评论 :: 0 Trackbacks

2008年6月17日 #

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace Sys
{
    [Serializable] 
//指示一个类可以序列化
    public class Element
    {
        
//复制对象
        public object DeepClone()
        {
            
object result = null;
            
using (MemoryStream ms = new MemoryStream()) //内存流
            {
                BinaryFormatter bf 
= new BinaryFormatter();//以二进制格式序列化对象
                bf.Serialize(ms, this);//将对象序列化为内存流
                ms.Seek(0, SeekOrigin.Begin);
                result 
= bf.Deserialize(ms); //将内存流反序列化为对象
            }
            
return result;
        }

        
//保存对象到文件
        
//(对象序列化到ms)→(ms写入byte[])→(byte[]写入流)
        public void WriteInstanceToFile(string fileName)
        {
            
using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bf 
= new BinaryFormatter();
                bf.Serialize(ms, 
this);
                ms.Seek(
0, SeekOrigin.Begin);
                
byte[] buffer = new byte[ms.Length];
                ms.Read(buffer, 
0, buffer.Length);
                ms.Seek(
0, SeekOrigin.Begin);

                FileStream stream 
= new FileStream(fileName, FileMode.Create);
                stream.Write(buffer,
0,buffer.Length);
            }
        }

        
//从文件中读取对象
        public static object ReadInstanceFromFile(string fileName)
        {
            
object result = null;
            FileStream stream 
= new FileStream(fileName, FileMode.Open);//以二进制格式序列化对象
            BinaryFormatter bf = new BinaryFormatter();
            result 
= bf.Deserialize((Stream)stream); //流反序列化为对象
            stream.Close();
            
return result;
        }
    }
}
posted @ 2008-06-17 13:04 StephenJu 阅读(44) | 评论 (0)编辑

2008年6月10日 #



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Sys
{
    
public partial class Form3 : Form
    {
        
public Form3()
        {
            InitializeComponent();
        }

        
private void Form3_Load(object sender, EventArgs e)
        {
            dataGridView1.AllowUserToAddRows 
= false;
            dataGridView1.AutoGenerateColumns 
= false;

            
using (SqlConnection sqlconn = new SqlConnection("server=.;uid=sa;pwd=sa;database=xx"))
            {
                
string sql1 = @"select userid,fullname,a.[description],b.ugroupid
                                from users a left outer join usergroup b 
                                on a.grade=b.ugroupid
";
                
string sql2 = "select distinct ugroupid,[description] from usergroup";

                DataGridViewComboBoxColumn dgvComboBoxColumn 
= dataGridView1.Columns["grade"as DataGridViewComboBoxColumn;
                dgvComboBoxColumn.DataPropertyName 
= "ugroupid";
                dgvComboBoxColumn.DataSource 
= GetTable(sql2).DefaultView;//必须在设置dataGridView1的DataSource的属性前设置
                dgvComboBoxColumn.DisplayMember = "description";
                dgvComboBoxColumn.ValueMember 
= "ugroupid";

                dataGridView1.DataSource 
= GetTable(sql1).DefaultView;//一定要在dgvComboBoxColumn的DataSource后设置
            }
        }

        
private DataTable GetTable(string sql)
        {
            
using (SqlConnection sqlconn = new SqlConnection("server=.;uid=sa;pwd=yuling1310;database=smls"))
            {
                DataTable dt 
= new DataTable();
                SqlDataAdapter sqlda 
= new SqlDataAdapter(sql, sqlconn);
                sqlda.Fill(dt);
                
return dt;
            }
        }
    }
}

注意事项:
.注意其ValueMember的DataType与DataPropertyName对应的列的DataType要相同,他不会为你做类型转换的。
2.编程设置显示样式时注意一定要在设置DataSource之前设置DataGridViewComboBoxColumn的DataSource等属性。
posted @ 2008-06-10 11:45 StephenJu 阅读(71) | 评论 (0)编辑

2008年5月28日 #

Validate Data in the Windows Forms DataGridView Control  
Samples:
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
// Validate the CompanyName entry by disallowing empty strings.
    if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
{
if (e.FormattedValue.ToString() == String.Empty)
{
dataGridView1.Rows[e.RowIndex].ErrorText =
"Company Name must not be empty";
e.Cancel = true;
}
}
}
posted @ 2008-05-28 21:29 StephenJu 阅读(110) | 评论 (0)编辑

2008年5月26日 #

//如果有超过一屏的数据,想通过关键字查找到相关记录,然后再定位之,做法如下:
//遍历所有行,把某单元格的值和关键字对比,找到后清除所有选择行,然后把当前行设为选择,然后把grid的CurrentCell设置为当前行的某个可见单元格即可,效果就会自动跳到定位好的行上。
     string str = textBox1.Text.Trim();
            foreach (DataGridViewRow dgvRow in dgvRoleInfo.Rows)
            {
                if(dgvRow.Cells[2].Value.ToString().StartsWith(str))
                {
                    dgvRoleInfo.ClearSelection();
                    dgvRow.Selected = true;
                    dgvRoleInfo.CurrentCell = dgvRow.Cells[2];
                    break;
                }
            }
posted @ 2008-05-26 15:33 StephenJu 阅读(48) | 评论 (0)编辑

Boolean createdNew; //返回是否赋予了使用线程的互斥体初始所属权
System.Threading.Mutex instance = new System.Threading.Mutex(true"MutexName"out createdNew); //同步基元变量
if (createdNew) //赋予了线程初始所属权,也就是首次使用互斥体
{
    Application.Run(
new Form1()); /s/这句是系统自动写的
    instance.ReleaseMutex();
}
else
{
    MessageBox.Show(
"已经启动了一个程序,请先退出!","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
    Application.Exit();
}
posted @ 2008-05-26 15:31 StephenJu 阅读(45) | 评论 (0)编辑

BULK INSERT 数据库名.dbo.[表名] --表名
   FROM 'd:\create_report.txt'--文本文件名
   WITH
      (
         FIELDTERMINATOR = '|',--字段结束符
         ROWTERMINATOR = '|\n'--行结束符
      )
posted @ 2008-05-26 15:30 StephenJu 阅读(21) | 评论 (0)编辑

        public class PositionData
        {
            
private string name; //字段
            private string ticker;//字段
            private string shares;//字段

            
public PositionData()
            {

            }

            
public PositionData(string name, string ticker, string shares)
            {
                
this.name = name;
                
this.ticker = ticker;
                
this.shares = shares;
            }

            
public string Name //属性
            {
                
get
                {
                    
return name;
                }
            }

            
public string Ticker //属性
            {
                
get
                {
                    
return ticker;
                }
            }

            
public string Shares //属性
            {
                
get
                {
                    
return shares;
                }
            }
        }

        ArrayList values 
= new ArrayList();
        values.Add(
new PositionData("Microsoft""Msft""150 共享")); 
        values.Add(
new PositionData("Intel""Intc""25 共享")); 
        values.Add(
new PositionData("Dell""Dell""115 共享"));
        
foreach (PositionData da in values)
        {
           
if (da.Name == "Microsoft")
              MessageBox.Show(da.Name.ToString()
+" "+da.Ticker.ToString()+" "+da.Shares.ToString(),"Info");
        }



//******************************使用泛******************************//
        
    List
<PositionData> tmp = new List<PositionData>();
        tmp.Add(
new PositionData("Microsoft""Msft""150 共享"));
        tmp.Add(
new PositionData("Intel""Intc""25 共享"));
        tmp.Add(
new PositionData("Dell""Dell""115 共享"));
        
for (int i = 0; i < tmp.Count; i++)
            MessageBox.Show(tmp[i].Name 
+ " " + tmp[i].Ticker + " " + tmp[i].Shares, "Info");
posted @ 2008-05-26 15:28 StephenJu 阅读(66) | 评论 (0)编辑

在写类库项目时,经常会有某些特殊业务需要用到服务器端的物理路径,使用传统的System.IO.Directory.GetCurrentDirectory()方法返回的则是WINNT\System32目录,这个一般不能满足正常的业务需求,而要得到具体运行DLL所在的物理目录可以通过Assembly.GetExecutingAssembly().CodeBase属性来取得,具体参考方法如下:

private string GetAssemblyPath()
        {
            string _CodeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase ;

            _CodeBase = _CodeBase.Substring(8,_CodeBase.Length - 8);    // 8是 file:// 的长度

            string[] arrSection = _CodeBase.Split(new char[]{'/'});
           
            string _FolderPath = "";
            for(int i=0;i<arrSection.Length-1;i++)
            {
                _FolderPath += arrSection[i] + "/";
            }

            return _FolderPath;
        }

 

public static string GetAssemblyPath()
{
 string _CodeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase ;

 _CodeBase = _CodeBase.Substring(8, _CodeBase.LastIndexOf("/")-8+1); // 8是 "file://" 的长度

 return _CodeBase.Replace("/", @"\");
}

posted @ 2008-05-26 15:28 StephenJu 阅读(41) | 评论 (0)编辑

假设我们的DataTable有5K左右的数据
那么,我们需要对他进行更加快速的操作
正常我们可能使用DataView.RowFilter来作
如果一两次都无所谓,如果要对DataView的RowFilter/Sort进行大批量的操作--该操作会导致DataTable索引重建.因为RowFilter Sort的设置会

导致DataView索引的建立
那么,是不建议的,应该使用
  1.设置DataView.Sort
  2.使用DataView.Find---判断是否存在数据,key=你在Sort里面定义的
     或者DataViewFindRow--获取Key对应的数据


PS:用datatable.select方法的时候,先后的检索顺序对检索时间是有影响的,这点和存储过程不一样。也不能忽视.

posted @ 2008-05-26 15:25 StephenJu 阅读(58) | 评论 (0)编辑

namespace t1
{
    
public abstract class myClass //不能被实例化
    {
        
public myClass() //总会被调用,否则无法创建带参构造函数
        {
            MessageBox.Show(
"基类的无参构造函数!");
        }
        
public myClass(int a) //要调用myClass(int a) 则必须“显式调用”,即在派生类中写成:public test(int a):base(a)
        {
            MessageBox.Show(
"{基类a!}");
        }
    }

    
public class test : myClass
    {
        
public test()
        {
            MessageBox.Show(
"派生类的无参构造函数!");
        }
        
public test(int a)
        {
            MessageBox.Show(
"{派生类a!}");
        }
    }
}

test t1=new test();
则输出: 基类的无参构造函数!
           派生类的无参构造函数!

test t2=new test(1);
则输出: 基类的无参构造函数!
           派生类a!

若写成如下:显示调用
public test(int a):base(a)
        {
            MessageBox.Show("{派生类a!}");
        }
test t3=new test(1);
则输出: 基类a!
           派生类a!


abstract用来修饰抽象类,表示该类只能作为父类被用于继承,而不能进行对象实例化。


 

posted @ 2008-05-26 15:18 StephenJu 阅读(27) | 评论 (0)编辑