搞了一天才搞出来给大家分享下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace WindowsApplication3
{
public partial class Form1 : Form
{
int i = 0;//i用来去顶其所在数据表的行号,一开始为第一行
DataSet ds;
SqlDataAdapter da;
string str = "Data Source=20111229-1228\\SQLEXPRESS;Initial Catalog=test;User ID=sa;Password=longhai";
string strsql = "select * from student";
SqlConnection cn;
public Form1()
{
InitializeComponent();
}
private void button8_Click(object sender, EventArgs e)
{
int k = 0;//用来确定要查找数据行的下标
if (textBox5.Text.Trim() == string.Empty)
{
MessageBox.Show("查找内容不能为空!");
textBox5.Focus();
}
else
for (k = 0; k < ds.Tables["student"].Rows.Count; k++)
if (ds.Tables["student"].Rows[k]["id"].ToString() == textBox5.Text) //找到textBox5.Text文本框中相匹配的数据行,其行号为k
{
i = k;
show(i);
break;
}
if (k == ds.Tables["student"].Rows.Count)
MessageBox.Show("无该学生信息");
textBox5.Text = "";
}
void show(int i)
{
try
{
if (ds != null)
ds.Clear();
else
{
ds = new DataSet();
da = new SqlDataAdapter(strsql, str);
}
//由于DataSet为断开连接的,因此在显示时对数据集重新填入,从而显示的为更新后的值
da.Fill(ds, "student");
DataRow dr = ds.Tables["student"].Rows[i];
textBox1.Text = dr["id"].ToString();
textBox2.Text = dr["name"].ToString();
textBox3.Text = dr["department"].ToString();
textBox4.Text = dr["age"].ToString();
pictureBox1.Image = Image.FromFile(dr["image"].ToString());
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
cn = new SqlConnection(str);
show(i);
}
private void button4_Click(object sender, EventArgs e)
{
i = 0;
show(i);
}
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection cn = new SqlConnection(str);
cn.Open();
SqlCommand Sqlcmd = new SqlCommand("select count(*) from student where id='" + textBox1.Text.Trim() + "'", cn);