0

嗨,我使用此代码在 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";
4

0 回答 0