c#之字符串的那些事儿

 

1.Format

Format(String, Object) 将指定字符串中的一个或多个格式项替换为指定对象的字符串表示形式。

ex1:简单示例怎么应用

1         private void btnTest_Click(object sender, EventArgs e) 2  { 3             string str = string.Format("您输入的信息为:{0}",txtTest.Text); 4  MessageBox.Show(str); 5         }

c#之字符串的那些事儿_第1张图片

ex2:数据库命令字符串的两种写法

第一种:

 

 1         private void btnInsert_Click(object sender, EventArgs e)  2  {  3             string strcon = @"Data Source=LON;Initial Catalog=Practice;Integrated Security=True";  4             SqlConnection conn = new SqlConnection(strcon);  5  conn.Open();  6 
 7             string strcmd = "insert into Info_Stu (Name,Age,Sex) values ('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"')";  8             SqlCommand cmd = new SqlCommand();  9             cmd.CommandText = strcmd; 10             cmd.CommandType = CommandType.Text; 11             cmd.Connection = conn; 12  cmd.ExecuteNonQuery(); 13         }

c#之字符串的那些事儿_第2张图片        c#之字符串的那些事儿_第3张图片

第二种:

 

 1         private void btnInsert_Click(object sender, EventArgs e)  2  {  3             string strcon = @"Data Source=LON;Initial Catalog=Practice;Integrated Security=True";  4             SqlConnection conn = new SqlConnection(strcon);  5  conn.Open();  6 
 7             string strcmd = string.Format("insert into Info_Stu (Name,Age,Sex) values ('{0}','{1}','{2}')", textBox1.Text, textBox2.Text, textBox3.Text);  8             SqlCommand cmd = new SqlCommand();  9             cmd.CommandText = strcmd; 10             cmd.CommandType = CommandType.Text; 11             cmd.Connection = conn; 12  cmd.ExecuteNonQuery(); 13         }

效果图同上,对比两条指令:

"insert into Info_Stu (Name,Age,Sex) values ('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"')";

 string strcmd = string.Format("insert into Info_Stu (Name,Age,Sex) values ('{0}','{1}','{2}')", textBox1.Text, textBox2.Text, textBox3.Text);

 

你可能感兴趣的:(c#之字符串的那些事儿)