ASP.NET操作DATAGRIDVIEW增加与修改记录源码
using System.Data;
using System.Data.SqlClient;
namespace HdhWinForm.DataManage
{
public partial class DataAdapterUpdate : Form
{
SqlConnection hdhcmsConn;
SqlDataAdapter hdhcmsSda;
DataSet hdhcmsDs;
public DataAdapterUpdate()
{
InitializeComponent();
}
private void DataAdapterUpdate_Load(object sender, EventArgs e)
{
string hdhcmsStrConn = "server=localhost;database=WinFormTest;uid=sa;pwd=sa123456";//定义数据库连接字符串变量
string hdhcmsStrSql = "select * from Employee "; //定义表查询语句变量
hdhcmsConn = new SqlConnection(hdhcmsStrConn);//实例化对象
SqlCommand hdhcmsComm = new SqlCommand(hdhcmsStrSql, hdhcmsConn);
hdhcmsSda = new SqlDataAdapter();
hdhcmsSda.SelectCommand = hdhcmsComm;
hdhcmsDs = new DataSet();
hdhcmsSda.Fill(hdhcmsDs, "hdhcmsFirst");
dataGridView1.DataSource = hdhcmsDs.Tables["hdhcmsFirst"];
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow hdhcmsDgvr = dataGridView1.Rows[e.RowIndex];
textBox1.Text = hdhcmsDgvr.Cells["id"].Value.ToString();
textBox2.Text = hdhcmsDgvr.Cells["name"].Value.ToString();
textBox3.Text = hdhcmsDgvr.Cells["sex"].Value.ToString();
textBox4.Text = hdhcmsDgvr.Cells["wages"].Value.ToString();
textBox1.ReadOnly = true;
button1.Text = "修改保存";
}
else
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
button1.Text = "新增保存";
}
}
private void button1_Click(object sender, EventArgs e)
{
//int id;
bool idBool = int.TryParse(textBox1.Text, out int id);
string name = textBox2.Text;
string sex = textBox3.Text;
string wages = textBox4.Text;
if (id > 0)
{
DataTable hdhcmsDt = hdhcmsDs.Tables["hdhcmsFirst"];
hdhcmsSda.FillSchema(hdhcmsDt, SchemaType.Mapped);
DataRow hdhcmsDr = hdhcmsDt.Rows.Find(id);
hdhcmsDr["name"] = name;
hdhcmsDr["sex"] = sex;
hdhcmsDr["wages"] = wages;
SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(hdhcmsSda);
hdhcmsSda.Update(hdhcmsDt);
MessageBox.Show("记录修改成功!");
}
else
{
DataTable hdhcmsNewDt = new DataTable();
hdhcmsNewDt.Columns.Add("name", typeof(string));
hdhcmsNewDt.Columns.Add("sex");
hdhcmsNewDt.Columns.Add("wages");
DataRow hdhcmsNewDr = hdhcmsNewDt.NewRow();
hdhcmsNewDr["name"] = name;
hdhcmsNewDr["sex"] = sex;
hdhcmsNewDr["wages"] = wages;
hdhcmsNewDt.Rows.Add(hdhcmsNewDr);
DataTable hdhcmsDt = hdhcmsDs.Tables["hdhcmsFirst"];
hdhcmsDt.Merge(hdhcmsNewDt);
SqlCommandBuilder hdhcmsScb = new SqlCommandBuilder(hdhcmsSda);
hdhcmsSda.Update(hdhcmsDt);
dataGridViewReload();
MessageBox.Show("新增数据成功!");
}
}
private void dataGridViewReload()
{
hdhcmsSda.Fill(hdhcmsDs, "hdhcmsFirst");
dataGridView1.DataSource = hdhcmsDs.Tables[0];
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
button1.Text = "新增保存";
}
}
}
查看更多关于ASP.NET操作DATAGRIDVIEW增加与修改记录源码的详细内容...