DataGridView Update 修改数据示例

.Net技术 码拜 9年前 (2015-01-06) 2327次浏览 0个评论
update的时候报这个错误
MySqlCommandBuilder sb = new MySqlCommandBuilder(m_da);
m_da.Update(m_dt);
m_da是dataadapter   m_dt是绑定的datatable
如下是 DataGridView Update 修改数据示例
//操作数据库类设置
class datatier
{
private SqlConnection GetConnection()
{
//返回连接到数据库的SqlConnection对象
return new SqlConnection(“server=WRET-MOSY688YVW\\MRGLL;database=db_test;Trusted_Connection=true”);
}
private List<Instance> GetList(SqlDataReader sdr)
{
List<Instance> lit = new List<Instance>();//定义集合对象
while (sdr.Read())//遍历SqlDataReader对象
{
//向集合对象内添加内容
lit.Add(new Instance() { Name = sdr[0].ToString(), phone = sdr[1].ToString() });
}
return lit;//返回集合对象
}//codego.net/tags/11/1/
public void Update(Instance it)
{
SqlConnection sc = GetConnection();//调用GetConnections()方法,得到连接对象
try
{
sc.Open();//打开到数据库的连接
SqlCommand cmd = new SqlCommand(//创建SqlCommand对象
“update tb_friend set phone=@phone where names=@names”, sc);
cmd.Parameters.Add(“@names”, SqlDbType.VarChar).Value = it.Name;//向SqlCommand对象添加参数
cmd.Parameters.Add(“phone”, SqlDbType.VarChar).Value = it.phone;//向SqlCommand对象添加参数
cmd.ExecuteNonQuery();//执行SqlCommand对象中的SQL命令
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (sc.State == ConnectionState.Open)//判断是否连接数据库
{
sc.Close();//如果已经连接则关闭连接
}
}
}
}
//绑定控件修改数据
private datatier dt = new datatier();//定义datatier类型的私有字段
private void btn_update_Click(object sender, EventArgs e)
{
//调用datatier对象的Update()方法,更改数据库中的信息
dt.Update(new Instance() { Name = txt_name_update.Text, phone = txt_phone_update.Text });
dataGridView1.DataSource = dt.Select();//更新dataGridView1控件中的信息
Clear();//清空TextBox控件中的文本
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明DataGridView Update 修改数据示例
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!