填充SQL Server数据表

时间:2016-05-21 03:31:04

标签: c# sql-server database

我的程序在执行后不会更新我的SQL Server数据库。当我运行我的程序时,我的DataGridView会在插入我的信息时更新,但它不会在dataTable中自行更新。

private void button1_Click(object sender, EventArgs e)
{
        string query = "INSERT INTO dbo.dataTable(Id,Name,Age) VALUES('" + idTextBox.Text + "','" + nameTextBox.Text + "','" + ageTextBox.Text + "')";

        SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\employee.mdf;Integrated Security=True;Connect Timeout=30");
        SqlCommand cmd;

        conn.Open();
        cmd = new SqlCommand(query, conn);
        cmd.ExecuteNonQuery();

        this.dataTableTableAdapter.Fill(this.employeeDataSet1.dataTable);
        conn.Close();

        SqlDataAdapter adapt = new SqlDataAdapter(cmd);
        DataTable data = new DataTable();

        conn.Open();
        adapt.Update(data);
        conn.Close();

        dataTableDataGridView.DataSource = data;
    }

2 个答案:

答案 0 :(得分:0)

如果您使用添加了数据集,bindingsource和tableadapter的设计器创建了DataGridView,那么您的DataGridView应该是开箱即用的。尝试注释掉这些内容:

>>> valid_list(["one", "two", "3"])
False

>>> valid_list(["one", "two", "3a"])
True

>>> valid_list(["one", "two", 0])
False

我复制了你的button_click代码,它使用Sql Express在本地工作。

答案 1 :(得分:0)

根据您的评论,我认为原因是缺少转换。使用Int32.TryParse可以将字符串转换为int。请注意'也必须

int id, age; 
bool idIsInt = false, ageIsInt = false;

idIsInt = Int32.TryParse(idTextBox.Text, out id);
ageIsInt = Int32.TryParse(ageTextBox.Text, out age);

if(idIsInt && ageIsInt)
{
 string query = "INSERT INTO dbo.dataTable(Id,Name,Age) VALUES(" 
        + id + ",'" + nameTextBox.Text + "'," 
        + age + ")";
 SqlConnection conn = 
 new SqlConnection(@"Data Source(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\employee.mdf
       ;Integrated Security=True;Connect Timeout=30");

 SqlCommand cmd;
 conn.Open();
 cmd = new SqlCommand(query, conn);
 cmd.ExecuteNonQuery();
}