我想设计一个包含文本框、按钮和 datagridview 的 UI,我可以在文本框中编写 SQL 查询,然后单击按钮,以便在 datagridview 中查看结果。是否有可能做到这一点?这是我的代码,如果我编写一个像“Select * From TableName”这样的 sql 语句并运行它,它会将表名显示为无效对象。谁能帮我解决这个问题?
private void btnSQLGenerator_Click(object sender, EventArgs e)
{
string serverName = textBoxTargetServer.Text;
var databaseName2 = comboBoxTargetDatabase.SelectedItem as string;
string connectionStr4 = "Data Source= " + serverName + ";Initial Catalog=" + databaseName2 + ";Integrated Security=True";
SqlCommand cmd4 = new SqlCommand();
using (SqlConnection conn4 = new SqlConnection(connectionStr4))
{
cmd4.Connection = conn4;
cmd4.CommandType = CommandType.Text;
cmd4.CommandText = textBox1.Text;
cmd4.Connection.Open();
SqlDataReader dr4 = cmd4.ExecuteReader();
dataGridView1.Rows.Add(dr4);
dataGridView1.DataSource = dr4.Read();
}
cmd4.Parameters.Clear();
cmd4.Connection.Close();
}