C#常用方法 【免费】

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C#常用方法【免费】
1.C#配置文件的使用
1.新建配置文件config
2.添加类引用using System.Configuration;
3.编写配置文件
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="sqlconn"connectionString="Data Source=localhost;Initial
Catalog=roommanege;Integrated Security=SSPI"/>
</connectionStrings>
</configuration>
4.在程序中引用配置文件
private void button4_Click(object sender, EventArgs e)
{
//string sqlconn = "Data Source=localhost;Initial Catalog=roommanege;Integrated Security=SSPI";
string sqlconn =
ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sqlconn))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
mandText = "select count(*) from admin where username=@username and pass=@pass";
cmd.Parameters.Add("username", textBox1.Text.Trim());
cmd.Parameters.Add("pass", textBox2.Text.Trim());
int i = Convert.ToInt32(cmd.ExecuteScalar());
if (i > 0)
{
MessageBox.Show("登录成功!");
}
else
{
MessageBox.Show("用户名或密码错误!");
}
}
}
}
2.登入模块
○1方法1
private void button2_Click(object sender, EventArgs e)
{
string sqlconn=
ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
// string connstring = "Data Source=localhost;Initial Catalog=roommanege;Integrated Security=SSPI";
using (SqlConnection conn = new SqlConnection(sqlconn))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
mandText = "select * from admin ";
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
richTextBox1.Text +=
reader.GetString(reader.GetOrdinal("username")) +
reader.GetString(reader.GetOrdinal("pass"));
}
}
}
}
}
○2方法2
private void button1_Click(object sender, EventArgs e)
{
//string connstring = "Data Source=localhost;Initial Catalog=roommanege;Integrated Security=SSPI";
string sqlconn =
ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
using (SqlConnection con = new SqlConnection(sqlconn))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
mandText = "select * from admin where username='" + textBox1.Text + "'";
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
string dbpassword =
reader.GetString(reader.GetOrdinal("pass")).Trim();
//string dbpassword = reader.GetString(reader.GetOrdinal("psd"));
if (dbpassword == textBox2.Text)
{
MessageBox.Show("登录成功!");
}
else
{
MessageBox.Show("密码错误!");
}
}
else
{
MessageBox.Show("用户名错误!");
}
reader.Close();
}
}
}
}
○3方法3
private void button4_Click(object sender, EventArgs e)
{
//string sqlconn = "Data Source=localhost;Initial Catalog=roommanege;Integrated Security=SSPI";
string sqlconn =
ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sqlconn))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
mandText = "select count(*) from admin where username=@username and pass=@pass";
cmd.Parameters.Add("username", textBox1.Text.Trim());
cmd.Parameters.Add("pass", textBox2.Text.Trim());
int i = Convert.ToInt32(cmd.ExecuteScalar());
if (i > 0)
{
MessageBox.Show("登录成功!");
}
else
{
MessageBox.Show("用户名或密码错误!");
}
}
}
}
3.两个Combox关联问题
private void Form1_Load(object sender, EventArgs e)
{
//string connstring = "Data Source=localhost;Initial Catalog=roommanege;Integrated Security=SSPI";
string sqlconn =
ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sqlconn))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
mandText = "select * from promary";
using (SqlDataReader datareader= cmd.ExecuteReader())
{
while (datareader.Read())
{
promary item = new promary();
=
datareader.GetString(datareader.GetOrdinal("proName")).Trim();
item.ID = datareader.GetInt32(datareader.GetOrdinal("proID"));
comboBox1.Items.Add(item);
}
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
promary item = (promary)comboBox1.SelectedItem;
int proID=item.ID;
//string connstring = "Data Source=localhost;Initial Catalog=roommanege;Integrated Security=SSPI";
string sqlconn =
ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sqlconn))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
mandText = "select * from city where proID=@proID";
cmd.Parameters.Add(new SqlParameter("proID", @proID));
using (SqlDataReader datareader = cmd.ExecuteReader())
{
comboBox2.Items.Clear();
while (datareader.Read())
{
string cityName =
datareader.GetString(datareader.GetOrdinal("cityName")).Trim();
comboBox2.Items.Add(cityName);
}
}
}
}
}
class promary
{
public string Name { get; set; }
public int ID { get; set; }
}
4.直接在VS上建数据库所需代码
String dataDir=AppDomain.CurrentDomain.BaseDirectory;
If (dataDir.EndsWith(@”\bin\Debug\”) || dataDir.EndsWith(@”\bin\Release\”)) {
dataDir=Sysem.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;
AppDomain.CurrentDomain.SetData(“DataDirectory”,dataDir);
}
5.数据导入
1.解压txt文件到指定目录
2.创建数据表
3.创建选择对话框
FolderBrowserDialog dlg=new FolderBrowserDialog();
If (dlg.ShowDialog()!=DialogResult.OK)
{
return;
String path=dlg.SelectedPath;
String []files=Directory.GetFiles(path,”*.txt”,SearchOption.AllDirectories);
Using (SqlConnection conn=new SqlConnection(connStr))
{
Conn.Open();
Using (SqlCommand= conn.CreateCommand())
{
mandText=”insert into T_Numbers(StarNo,EndNo,Name) values (@StarNo,@EndNo,@Name)”; Foreach (string file in files)
{
String 运营商名称=Path.GetFileNameWithoutExtension(file);
String [] lines=File.ReadAllLines(file,Encoding.Default);
Foreach (string line in lines)
{
String []strs=line.Split(…-‟);
String 开始号码=strs[0];
String 结束号码=strs[1];
String 市 =strs[2];
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter(“StarNo”,开始号码));
cmd.Parameters.Add(new SqlParameter(“EndNo”,结束号码));
cmd.Parameters.Add(new SqlParameter(“Name” ,运营商名称+市));
cmd.ExecuteNonQuery();
}
}
}
}
6.数据封装
1.新建一个数据类SQLHelp.cs
class SQLHelp
{
public static int ExecuteNonQuery (string sql ,params SqlParameter []paramesters)
{
string
sqlconn=ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
using (SqlConnection conn=new SqlConnection(sqlconn))
{
conn.Open();
using(SqlCommand cmd=conn.CreateCommand())
{
mandText=sql;
foreach(SqlParameter paramester in paramesters)
{
cmd.Parameters.Add(paramester);
}
return cmd.ExecuteNonQuery();
}
}
}
public static object ExecuteScalar(string sql,params SqlParameter []paramesters)
{
string sqlconn =
ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
using(SqlConnection conn=new SqlConnection(sqlconn))
{
conn.Open();
using(SqlCommand cmd=conn.CreateCommand())
{
mandText = sql;
foreach (SqlParameter paramester in paramesters)
{
cmd.Parameters.Add(paramester);
}
return cmd.ExecuteScalar();
}
}
}
public static DataTable ExecuteDataTable(string sql,params SqlParameter []parmesters) {
string sqlconn =
ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
using (SqlConnection conn=new SqlConnection(sqlconn))
{
conn.Open();
using(SqlCommand cmd=conn.CreateCommand())
{
mandText = sql;
foreach(SqlParameter paramester in parmesters)
{
cmd.Parameters.Add(paramester);
}
DataSet dataset = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataset);
DataTable table = dataset.Tables[0];
return table;
}
}
}
}
3.调用SQLHelp
private void button5_Click(object sender, EventArgs e)
{
SQLHelp.ExecuteNonQuery("insert into admin(ano,username,pass) values (@ano,@username,@pass)", new SqlParameter("ano", textBox1.Text.Trim()), new SqlParameter("username", textBox2.Text.Trim()), new SqlParameter("pass",
textBox3.Text.Trim()));
}
private void button7_Click(object sender, EventArgs e)
{
object i = SQLHelp.ExecuteScalar("select count (*) from admin");
MessageBox.Show(Convert.ToString(i));
}
private void button8_Click(object sender, EventArgs e)
{
DataTable dt = SQLHelp.ExecuteDataTable("select * from admin where username=@username",new SqlParameter("username",textBox1.Text.Trim()));
if (dt.Rows.Count<=0)
{
MessageBox.Show("找不到用户名!");
return;
}
else
{
DataRow row=dt.Rows[0];
string dbpass = Convert.ToString(row["pass"]).Trim();
MessageBox.Show(dbpass);
if (textBox2.Text.Trim()==dbpass)
{
MessageBox.Show("登录成功!");
}
else
{
MessageBox.Show("密码错误!");
}
}
}
7.将查询结果显示到dataGridView中
private void button9_Click(object sender, EventArgs e)
{
/*string sqlconn =
ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
using(SqlConnection conn=new SqlConnection(sqlconn))
{
conn.Open();
using(SqlCommand cmd=conn.CreateCommand())
{
mandText="select * from admin where ano=@ano";
cmd.Parameters.Add("ano", textBox1.Text.Trim());
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
this.dataGridView1.DataSource = dataset.Tables[0].DefaultView;
}
}*/
DataTable table= SQLHelp.ExecuteDataTable("select * from admin where ano=@ano", new SqlParameter("ano", textBox1.Text.Trim()));
this.dataGridView1.DataSource = table.DefaultView;
}
8. BindingNavigator1和DataGridView1的使用
private BindingSource bs = new BindingSource();
private void Form1_Load(object sender, EventArgs e)
{
string strConn = ConfigurationManager.ConnectionStrings["NORTHWND"].ConnectionString;
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
DataSet ds = new DataSet();
string sql = "SELECT * FROM Orders";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(ds);
conn.Close();
bs.DataSource = ds.Tables[0];
bindingNavigator1.BindingSource = bs;
dataGridView1.DataSource = bs;
}
}
}
9.存储过程的调用
public static DataTable ExecuteDataTable (string sql,params SqlParameter []parmesters)
{
string sqlconn =
ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
using (SqlConnection conn=new SqlConnection(sqlconn))
{
conn.Open();
using(SqlCommand cmd=conn.CreateCommand())
{
mandText = sql;
foreach(SqlParameter paramester in parmesters)
{
cmd.Parameters.Add(paramester);
}
DataSet dataset = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
mandType = CommandType.StoredProcedure;//带参数必须写这句
adapter.Fill(dataset);
DataTable table = dataset.Tables[0];
return table;
}
}
}
public static int ExecuteNonQuery (string sql ,params SqlParameter []paramesters)
{
string
sqlconn=ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
using (SqlConnection conn=new SqlConnection(sqlconn))
{
conn.Open();
using(SqlCommand cmd=conn.CreateCommand())
{
mandText=sql;
mandType = CommandType.StoredProcedure;
foreach(SqlParameter paramester in paramesters)
{
cmd.Parameters.Add(paramester);
}
return cmd.ExecuteNonQuery();
}
}
}
○1不带参数的存储过程
private void button10_Click(object sender, EventArgs e)
{
/* string sqlconn =
ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
using(SqlConnection conn=new SqlConnection(sqlconn))
{
conn.Open();
using(SqlCommand cmd =conn.CreateCommand())
{
mandText = "EXEC S_roominfo";
cmd.ExecuteNonQuery();
}
}*/
DataTable table = SQLHelp.ExecuteDataTable("S_roominfo");
this.dataGridView1.DataSource = table.DefaultView;
BindingSource bs = new BindingSource();
bs.DataSource = table;
bindingNavigator1.BindingSource = bs;
this.dataGridView1.DataSource = bs;
}
○2带参数存储过程的调用
private void button11_Click(object sender, EventArgs e)
{
DataTable table = SQLHelp.ExecuteDataTable("s_roominfotype",new SqlParameter("@roomtype",textBox1.Text.Trim()));
this.dataGridView1.DataSource = table.DefaultView;
BindingSource bs = new BindingSource();
bs.DataSource = table;
bindingNavigator1.BindingSource = bs;
this.dataGridView1.DataSource = bs;
}
private void button12_Click(object sender, EventArgs e)
{
SQLHelp.ExecuteNonQuery("Insert_admin", new SqlParameter("@ano", textBox1.Text.Trim()), new SqlParameter("@username", textBox2.Text.Trim()), new SqlParameter("@pass", textBox3.Text.Trim()));
MessageBox.Show("添加成功");
}
10.报表的使用
1.新建一个数据集MyDataSource,往数据集中拖放一个TableAdapter控件,编写SQL语句
2.新建一个CrystalReport1水晶报表控件,设置报表要显示的格式,内容,分组,汇总…
3.在Form窗体中放上crystalReportViewer1控件
private void Form1_Load(object sender, EventArgs e)
{
string sqlconn =
ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
using (SqlConnection conn=new SqlConnection(sqlconn))
{
conn.Open();
MyDataSource MyData = new MyDataSource();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM course INNER JOIN sc ON o = o INNER JOIN student ON sc.sno = student.Sno", conn);
adapter.Fill(MyData, "DataTable1");
CrystalReport1cr=new CrystalReport1();
cr.SetDataSource(MyData);
crystalReportViewer1.ReportSource = cr;
}
}
你是在form1中打开form3,操作完form3后,刷新form1吗?
可以用这种方法:
//form1:
form3 f3 = new form3();
f3.Owner = this;
f3.ShowDialog();
public void Refresh_Method(){xxx}
//form3:
form1 f1 = new form1();
f1 = (form1)this.Owner;
f1.Refresh_Method();
这样即可实现子窗体对父窗体的刷新了。

连接服务器和数据库
private void comboBox1_DropDown(object sender, EventArgs e)
{
SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass();
List sqlServers = sqlApp.ListAvailableSQLServers(); for (int i = 0; i < sqlServers.Count; i++)
{
object srv = sqlServers.Item(i + 1);
if (srv != null)
{
boBox1.Items.Add(srv);
}
} }
private void comboBox2_DropDown(object sender, EventArgs e)
{
SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass();
SQLDMO.SQLServer srv = new SQLDMO.SQLServerClass();
comboBox2.Items.Clear();
srv.Connect(comboBox1.Text, "sa", "");
if (srv.Databases.Count > 0)
{
foreach (SQLDMO.Database db in srv.Databases)
{
if ( != null)
{
comboBox2.Items.Add();
}
}
}
}。

相关文档
最新文档