using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient; //sql 引用
using System.Configuration; //app.config 引用
namespace SqlGetState
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con;
SqlDataAdapter sda;
DataTable dt;
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e) //获取数据
{
string conString = ConfigurationManager.ConnectionStrings["GetSqlCon"].ConnectionString;
con = new SqlConnection(conString);
string sql = "select * from xs";
sda = new SqlDataAdapter(sql, con);
dt = new DataTable();
sda.Fill(dt);
this.dataGridView1.DataSource = dt;
SqlCommandBuilder cb = new SqlCommandBuilder(sda);
try
{
con.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
con.Close();
}
for (int i = 0; i < dt.Rows.Count; i++)
{
//this.listBox1.Items.Add(row[i].RowState);
this.listBox1.Items.Add(this.dt.Rows[i].RowState);
}
}
private void button2_Click(object sender, EventArgs e) //更改数据
{
try
{
// con.Open();
this.listBox1.Items.Clear(); //清空listBox1控件
for (int i = 0; i < dt.Rows.Count; i++)
{
//this.listBox1.Items.Add(row[i].RowState);
this.listBox1.Items.Add(this.dt.Rows[i].RowState); //读取状态
}
sda.Update(dt); //更新数据
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
// con.Close();
}
}
}
}
app.config
using System.Configuration;
添加 System.Configuration;引用
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="GetSqlCon" connectionString="Data Source=.;DataBase=xsgl;Integrated Security=True;" providerName="System.Data.SqlClinet"/>
</connectionStrings>
</configuration>
转载于:https://blog.51cto.com/mtlang/1086129