当SELECT查询具有WHERE条件时,插入到datagridview

时间:2013-04-09 06:49:11

标签: c# datagridview insert

您好我使用此代码在C#windows应用程序中使用datagridview将数据加载到表中。

        SqlCommand sCommand;
        SqlDataAdapter sAdapter;
        SqlCommandBuilder sBuilder;
        DataSet sDs;
        DataTable sTable;          
private void form1_Load(object sender, EventArgs e)
            {    
                string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True;User Instance=True";
                string sql = "SELECT * FROM mytable";
                SqlConnection connection = new SqlConnection(connectionString);
                connection.Open();
                sCommand = new SqlCommand(sql, connection);
                sAdapter = new SqlDataAdapter(sCommand);
                sBuilder = new SqlCommandBuilder(sAdapter);
                sDs = new DataSet();
                sAdapter.Fill(sDs, "mytable");
                sTable = sDs.Tables["mytable"];
                connection.Close();
                dataGridView1.DataSource = sDs.Tables["mytable"];
                dataGridView1.ReadOnly = true;
                save_btn.Enabled = false;
                dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            }

            private void new_btn_Click(object sender, EventArgs e)
            {
                dataGridView1.ReadOnly = false;
                save_btn.Enabled = true;
                new_btn.Enabled = false;
                delete_btn.Enabled = false;
            }

            private void delete_btn_Click(object sender, EventArgs e)
            {
                if (MessageBox.Show("Are you sure?", "Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
                    sAdapter.Update(sTable);
                }
            }

            private void save_btn_Click(object sender, EventArgs e)
            {
                sAdapter.Update(sTable);
                dataGridView1.ReadOnly = true;
                save_btn.Enabled = false;
                new_btn.Enabled = true;
                delete_btn.Enabled = true;
            }
        }

没关系,但是当我尝试使用具有条件的查询时,没有行添加到datagrid和mytable

sql = "SELECT * FROM mytable where col2 = 1";

0 个答案:

没有答案