天津理工大学C#期末复习总结

发布时间:2019-09-06 14:55:35   来源:文档文库   
字号:

C#资料

一、 数据库相关

连接字符串

Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;

string sqlConnection="DATA SOURCE=(local);DATABASE=DB;USER ID=SA;PWD=123";

public static readonly string connstr = "Data Source=vmb72;Initial Catalog=SCHOOL;Integrated Security=True;Connect Timeout=15";

"Data Source=C:\BegASPNET\Northwind.mdb"是指明数据源的位置,他的标准形式是"Data Source=MyDrive:MyPath\MyFile.MDB". PS: 1."+="后面的"@"符号是防止将后面字符串中的"\"解析为转义字符. 2.如果要连接的数据库文件和当前文件在同一个目录下,还可以使用如下的方法连接: strConnection+="Data Source=";strConnection+=MapPath("Northwind.mdb"; 这样就可以省得你写一大堆东西了! 3.要注意连接字符串中的参数之间要用分号来分隔. "OleDbConnection objConnection=new OleDbConnection(strConnection);"这一句是利用定义好的连接字符串来建立了一个链接对象,以后对数据库的操作我们都要和这个对象打交道.

打开连接

SqlConnection conn = new SqlConnection(connstr);

conn.Open();

操作SqlCommand sqlcom = new SqlCommand("insert into info(id,name,sex) values( " + i + ",'" + s1 + "','" + s2 + "')", objSqlConnection); 

sqlcom.ExecuteNonQuery();

填充

DataTable dt1 = new DataTable(); 

SqlDataAdapter da1 = new SqlDataAdapter();

string query = "SELECT * from info where id="+i;

 DataSet objDataSet = new DataSet(); 

SqlDataAdapter obj = new SqlDataAdapter(); 

obj.SelectCommand = new SqlCommand(query, objSqlConnection); 

obj.Fill(objDataSet, "info");

SqlCommand objSqlCommand = new SqlCommand(query, objSqlConnection); SqlDataReader objSqlReader = objSqlCommand.ExecuteReader();

数据库连接示例

static public SqlConnection GetConn()

{

string connString = null;

connString =System.Configuration.ConfigurationManager.AppSettings["ConnString"];

SqlConnection conn = new SqlConnection(connString);

return conn;

}// 执行select语句,返回DataTable对象

static public DataTable QueryBySql(string sqlStr)

{

DataTable dt = null;

SqlConnection conn = null;

SqlDataAdapter da = null;

try

{

dt = new DataTable();

conn = GetConn();

da = new SqlDataAdapter(sqlStr, conn);

da.Fill(dt);

}

catch (Exception ex)

{

throw ex;

}

finally

{

dt.Dispose();

da.Dispose();

conn.close();

conn.Dispose();

}

return dt;

}

// 执行insert intoupdatedelete

static public int SqlCmdOperation(string sqlText)

{

SqlConnection conn = null;

SqlCommand cmd = null;

int count = 0;

try

{

conn = GetConn();

cmd = new SqlCommand(sqlText, conn);

if (conn.State != ConnectionState.Open)

conn.Open();

count = cmd.ExecuteNonQuery();

}

catch (Exception ex)

{

throw (ex);

}

finally

{

cmd.Dispose();

conn.Close();

conn.Dispose();

}

return count;

}

二、 listview

1. listview更新

LvCourse.Items.Clear();

DataTable CourerInfo = SqlHelper.ExecuteDataTable("select * from dbo.Course order by Cno");

LvCourse.BeginUpdate();

for (int i = 0; i < CourerInfo.Rows.Count; i++)

{

DataRow Course = CourerInfo.Rows[i];

ListViewItem Cou = new ListViewItem();

Cou.Text = Course["Cno"].ToString(); //设置第一列

Cou.SubItems.Add(Course["Cname"].ToString());//设置其他列

Cou.SubItems.Add(Course["Cpno"].ToString());

Cou.SubItems.Add(Course["Ccredit"].ToString());

LvCourse.Items.Add(Cou);

}

LvCourse.EndUpdate();

listview中填充数据应先把listview view属性设置为detailsFullrowselect属性可以设置为true(整行选择)。Gridlines属性设置为truelistview中显示表格线。

2. listview选中行

private void LvStudent_SelectedIndexChanged(object sender, EventArgs e)

{

if (LvStudent.SelectedItems.Count > 0)

{

i = Convert.ToInt32(LvStudent.SelectedItems[0].Index.ToString());

TBSno.Text = LvStudent.Items[i].SubItems[0].Text;

TBSname.Text = LvStudent.Items[i].SubItems[1].Text;

TBSsex.Text = LvStudent.Items[i].SubItems[2].Text;

TBSage.Text = LvStudent.Items[i].SubItems[3].Text;

TBSdept.Text = LvStudent.Items[i].SubItems[4].Text;

}

}

3. 其他

提示框:

DialogResult res = MessageBox.Show("确定要删除学号为" + TBSno.Text.Trim() + "的学生?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

if (res == DialogResult.Yes)

{

}

点击按钮

btnRefreshGrade.PerformClick();

三、 文件操作

1.选择目录

FolderBrowserDialog fbd = new FolderBrowserDialog();

fbd.Description = "请选择目录";

fbd.RootFolder = Environment.SpecialFolder.MyComputer;

if (fbd.ShowDialog() == DialogResult.OK)

{

}

2.填充listview

listView1.Clear();

try

{

foreach (string dirname in Directory.GetDirectories(dirfilename))

{

ListViewItem itemlist = new ListViewItem(dirname);

listView1.Items.Add(itemlist);

}

foreach (string filename in Directory.GetFiles(dirfilename))

{

ListViewItem itemlist = new ListViewItem(filename);

listView1.Items.Add(itemlist);

}

}

catch { }

应将listviewview属性设置为list

View:获取或设置项在控件中的显示方式,包括DetailsLargeIconListSmallIconTile(默认为 LargeIcon

MultiSelect:设置是否可以选择多个项。(默认为false

代码创建listview列标头

1.

2.

3.

4.

5.

6.

7.

8.

9.

行高设置(利用imageList实现)

1.

2.

3.

清空

1.

2.

其他

filefolder = Path.GetDirectoryName(str)+@"\";获取当前文件所在文件夹

Program.pathx.ToLower().EndsWith(".txt")判断当前字符串

File.Copy(Program.pathx, fbd.SelectedPath + @"\" + filename);复制文件

System.Diagnostics.Process.Start(Program.pathx); 打开文件

File.Exists(d)判断文件是否存在

File.Move(filefolder + filename, filefolder + newname.Text);重命名文件

删除文件夹

public void DeleteFolder(string dir)//删除文件夹

{

foreach (string d in Directory.GetFileSystemEntries(dir))

{

if (File.Exists(d))

{

FileInfo fi = new FileInfo(d);

if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)

fi.Attributes = FileAttributes.Normal;

File.Delete(d);//直接删除其中的文件

}

else

DeleteFolder(d);//递归删除子文件夹

}

Directory.Delete(dir);//删除已空文件夹

}

读取txt

StreamReader sr = new StreamReader(Program.pathx, Encoding.Default);

String line;

while ((line = sr.ReadLine()) != null)

{

str += line.ToString();

}

四、 webbrowser

设置控件位置

this.webBrowser1.Size = new System.Drawing.Size(772, this.Height-60);

this.tbUrl.Size = new System.Drawing.Size(this.Width-200, 20);

this.button1.Location = new System.Drawing.Point(this.Width-110, 10);

webbrowser控件设置

webBrowser1.Navigate(tbUrl.Text.Trim()); //前往网址

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) //控件加载完网页事件

{

button1.Enabled = true;

tbUrl.Text = webBrowser1.Url.ToString();

}

五、 C#基础

素数

private bool fun2(int x)

{

bool flag = true;

for (int i = 2; i <= Math.Sqrt(x); i++)

{

if (x%i == 0)

{

flag = false;

break;

}

}

return flag;

}

闰年

private bool fun3(int year)

{

if (year%4 == 0 && year%100 != 0 || year%400 == 0)

{

return true;

}

else

{

return false;

}

}

整数倒排

private int fun4(int x)

{

int result = 0;

while (x > 0)

{

int yushu = x % 10;

result = result * 10 + yushu;

x = x / 10;

}

return result;

}

(6) 是否是回文(正读和反读相同)

private bool fun5(string str)

{

bool result = true;

int i = 0;

int j = str.Length - 1;

while (i < j)

{

if (str[i] == str[j])

{

i++;

j--;

}

else

{

result = false;

break;

}

}

return result;

}

求最大数

private int fun6(int[] a)

{

int max = a[0];

int n = a.Length;

for (int i = 1; i < n; i++)

{

if (a[i] > max)

max = a[i];

}

return max;

}

从小到大排序(冒泡排序)

private void fun7(int[] a)

{

int min;

int n = a.Length;

for (int i = 0; i < n - 1; i++)

{

min = i;

for (int j = i + 1; j < n; j++)

{

if (a[j] < a[min])

{

min = j;

}

}

int tmp = a[i];

a[i] = a[min];

a[min] = tmp;

}

}

将数组中 x 的倍数变为 0

private void fun8(int[] a, int x)

{

int n = a.Length;

for (int i = 0; i < n; i++)

{

if (a[i]%x == 0)

{

a[i] = 0;

}

}

}

求最大公约数

private int fun9(int m, int n)

{

int r;

do

{

r = m % n;

if (r != 0)

{

m = n;

n = r;

}

} while (r != 0);

return n;

}

奇数或偶数和

private int getSum()

{

int intSum = 0;

for (int i = 0; i <= 100; i++)

{

if (i % 2 = = 0)

continue;

intSum = intSum + i;

}

return intSum;

}

六、 Combox

初始化

ComboBoxItem cbi1 = new ComboBoxItem();cbi1.Text = "测试Test1";cbi1.Value = "测试Value1";comboBox1.Items.Add(cbi1);

或者直接写

comboBox1.Items.Add(条目);

使用

if (comboBox1.Items != null && comboBox1.Items.Count > 0 && comboBox1.SelectedItem != null){string text = ((ComboBoxItem)comboBox1.SelectedItem).Text;object vlaue = ((ComboBoxItem)comboBox1.SelectedItem).Value;}

其他

dropdownstyle属性改为dropdownlistcombox内容不可编辑

设置combox默认值:设置combox.SelectedIndex=0;前提是comboxitems属性里有值

七、 C#字符串函数

Compare 比较字符串的内容,考虑文化背景(场所),确定某些字符是否相等CompareOrdinalCompare一样,但不考虑文化背景Format 格式化包含各种值的字符串和如何格式化每个值的说明符IndexOf 定位字符串中第一次出现某个给定子字符串或字符的位置IndexOfAny定位字符串中第一次出现某个字符或一组字符的位置LastIndexOfIndexOf一样,但定位最后一次出现的位置 LastIndexOfAnyIndexOfAny,但定位最后一次出现的位置PadLeft 在字符串的开头,通过添加指定的重复字符填充字符串PadRight在字符串的结尾,通过添加指定的重复字符填充字符串Replace 用另一个字符或子字符串替换字符串中给定的字符或子字符串2Int32.Parse(变量) Int32.Parse("常量") 字符型转换 转为32位数字型3 变量.ToString() 字符型转换 转为字符串 12345.ToString("n"); //生成 12,345.00 12345.ToString("C"); //生成 12,345.00 12345.ToString("e"); //生成 1.234500e+004 12345.ToString("f4"); //生成 12345.0000 12345.ToString("x"); //生成 3039 (16进制) 12345.ToString("p"); //生成 1,234,500.00%

4、变量.Length 数字型 取字串长度: 如: string str="中国"; int Len = str.Length ; //Len是自定义变量, str是求测的字串的变量名

5System.Text.Encoding.Default.GetBytes(变量) 字码转换 转为比特码 如:byte[] bytStr = System.Text.Encoding.Default.GetBytes(str); 然后可得到比特长度:len = bytStr.Length; 6System.Text.StringBuilder("")

字符串相加,(+号是不是也一样?) 如:System.Text.StringBuilder sb = new System.Text.StringBuilder(""); sb.Append("中华"); 7、变量.Substring(参数1,参数2); 截取字串的一部分,参数1为左起始位数,参数2为截取几位。 如:string s1 = str.Substring(0,2);

8String user_IP=Request.ServerVariables["REMOTE_ADDR"].ToString(); 取远程用户IP地址9Math.Max(i,j) ij中的最大值, int x=Math.Max(5,10); // x将取值 10

10、字串对比一般都用: if(str1==str2){ } , 但还有别的方法: (1) string str1; str2 //语法: str1.EndsWith(str2); __检测字串str1是否以字串str2结尾,返回布尔值.: if(str1.EndsWith(str2)){ Response.Write("字串str1是以"+str2+"结束的"); } (2)//语法:str1.Equals(str2); __检测字串str1是否与字串str2相等,返回布尔值,用法同上.

(3)//语法 Equals(str1,str2); __检测字串str1是否与字串str2相等,返回布尔值,用法同上. 11IndexOf() LastIndexOf() 查找字串中指定字符或字串首次(最后一次)出现的位置,返回索引值,如: str1.IndexOf("") //查找“字”在str1中的索引值(位置) str1.IndexOf("字串")//查找“字串”的第一个字符在str1中的索引值(位置) str1.IndexOf("字串",3,2)//str14个字符起,查找2个字符,查找“字串”的第一个字符在str1中的索引值(位置) 12Insert() 在字串中指定索引位插入指定字符。如: str1.Insert(1,"");str1的第二个字符处插入“字”,如果str1="中国",插入后为“中字国”;

13.string str1; str2 //语法: str1.EndsWith(str2); __检测字串str1是否以字串str2结尾,返回布尔值.: if(str1.EndsWith(str2)){ Response.Write("字串str1是以"+str2+"结束的"); } 2 语法:str1.Equals(str2); __检测字串str1是否与字串str2相等,返回布尔值,用法同上. 3 //语法 Equals(str1,str2); __检测字串str1是否与字串str2相等,返回布尔值,用法同上.IndexOf() 查找字串中指定字符或字串首次出现的位置,返首索引值,如: str1.IndexOf("") //查找“字”在str1中的索引值(位置) str1.IndexOf("字串")//查找“字串”的第一个字符在str1中的索引值(位置) str1.IndexOf("字串",3,2)//str14个字符起,查找2个字符,查找“字串”的第一个字符在str1中的索引值(位置)

14.统计字符串中英文单词数量

string text = "My name is JiangGujin,I come from China";             

string[] str = text.Split(' ', ',', '.', '?', '!', ':');          

Console.WriteLine("单词个数为:{0}",str.Length); 

15.统计汉字

int count = 0;
    Regex regex = new Regex(@"^[\u4E00-\u9FA5]{0,}$");

    for (int i = 0; i < str.Length; i++)
    {
        if (regex.IsMatch(str[i].ToString()))
        {
            count++;
        }
    }

16.判断数字

int a = 0;

if (int.TryParse(TBSno.Text.Trim(), out a) == false)

{

MessageBox.Show("学号是纯数字!请重新输入!"); //判断输入的学号是否是纯数字 }

17.统计长度

int len=0;

for(int i=0;i

{

byte[] byte_len = Encoding.Default.GetBytes(Text.Substring(i,1));

if(byte_len.Length>1)

len += 2; //如果长度大于1,是中文,占两个字节,+2

else

len += 1; //如果长度等于1,是英文,占一个字节,+1

}

本文来源:https://www.2haoxitong.net/k/doc/2d500d5bcfc789eb172dc8c7.html

《天津理工大学C#期末复习总结.doc》
将本文的Word文档下载到电脑,方便收藏和打印
推荐度:
点击下载文档

文档为doc格式