private void button6_Click(object sender, EventArgs e)
{
string serverName = textBox1.Text;
string dbName = textBox4.Text;
string username = textBox2.Text;
string password = textBox3.Text;
string tableName = textBox6.Text;
string connectionString = $"Server={serverName};Database={dbName};User Id={username};Password={password};";
using (SqlConnection fetchConnection = new SqlConnection(connectionString))
{
// connection.Open();
// Check if the connection is open
// if (connection == null || connection.State != ConnectionState.Open)
// {
// MessageBox.Show("Please establish a database connection first.", "Connection Required", MessageBoxButtons.OK, MessageBoxIcon.Warning);
// return;
// }
// Fetch data from the SQL data source
SqlDataAdapter adapter = new SqlDataAdapter($"SELECT sc.name as [Column Name]\r\n\r\nFROM sys.all_columns sc\r\n\r\nJOIN sys.tables st\r\n\r\n ON st.object_id = sc.object_id\r\n\r\nWHERE st.name = '{tableName}' --and schema_id in ('16', '15')\r\n\r\nORDER BY st.name", fetchConnection); //Select YourTable
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
// If you want to rename a column to "Column2"
// dataTable.Columns["Column Name"].ColumnName = "Column2";
// Bind the DataGridView to the retrieved data
dataGridView1.DataSource = dataTable;
// dataGridView2.DataSource = dataTable;
// Replace with your column name
dataGridView1.Columns["Column3"].DataPropertyName = "ColumnNameP";
}
}
Question: I wish to display SQL source data to the datagridview column where I created by using edit column. Unfortunately, it won't works. Something missing out there. Expert help required.
1条答案
按热度按时间vhmi4jdf1#