我在c#中有一个datagridview,我用我想要的数据库中的任何表填充它,从文本框中获取表名。一切都很好,直到我试图将我在datagridview中做的更改提交到数据库。通过dataGridView更新数据库
button2是我将用于更新的按钮。我搜遍了所有,显然更新适配器应该工作,但它不在这种情况下,我不明白为什么。这里是我的代码:
public partial class Form1 : Form
{
static string connstr = "DataSource=localhost;Database=sc2db;Trusted_Connection=True;";
SqlConnection conn = new SqlConnection(connstr);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlDataAdapter adap = new SqlDataAdapter();
DataTable dt = new DataTable();
//BindingSource bs = new BindingSource();
SqlCommand comm = new SqlCommand("select * from " + textBox1.Text, conn);
adap.SelectCommand = comm;
dataGridView1.DataSource = dt;
adap.Fill(dt);
}
catch (Exception ex)
{
label1.Text = ex.Message;
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
SqlDataAdapter adap = new SqlDataAdapter();
DataTable dt = new DataTable();
BindingSource bs = new BindingSource();
adap.Update(dt);
}
catch (Exception ex)
{
label1.Text = ex.Message;
}
}
}
我编辑了自己的冠军。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 –
我会记住这一点。我的道歉,我在这里比较新。 – icarus
我写了一篇关于此的帖子。可能这会帮助你http://yadavsachin.wordpress.com/2012/07/31/save-dataset-changes-to-database-in-c/ – Sachin