Note that there are some explanatory texts on larger screens.

plurals
  1. PODataGridView: Determine SQL Key Values or Relationships?
    primarykey
    data
    text
    <p>Is there a way to tell when a <code>DataGridView</code> columns is a <code>PRIMARY KEY</code> or a <code>FOREIGN KEY</code>?</p> <p>The reason I ask is because I'd like to set these <code>DataGridViewDataColumns</code> to be <code>ReadOnly</code>.</p> <p>After loading a <code>DataTable</code>, I can see SQL-like properties like <em>AllowDBNull</em>, <em>AutoIncrement</em>, and <em>Unique</em>; but how do I tell which columns are keys?</p> <pre><code>private void GetData(string tableName, SqlConnection con) { bool wasOpen = (con.State == ConnectionState.Open); DataTable table = new DataTable(tableName); string sqlText = string.Format(SQL_SELECT_COMMAND, tableName); SqlCommand cmd = new SqlCommand(sqlText, con); if (!wasOpen) { con.Open(); } table.Load(cmd.ExecuteReader()); if (!wasOpen) { con.Close(); } dataGridView1.DataSource = table.DefaultView; for (int i = 0; i &lt; table.Columns.Count; i++) { DataColumn tblC = table.Columns[i]; DataGridViewColumn dgvC = dataGridView1.Columns[i]; dgvC.ReadOnly = (!tblC.AllowDBNull &amp;&amp; tblC.AutoIncrement &amp;&amp; tblC.Unique); } } </code></pre> <p>The test in that last line above (<code>!tblC.AllowDBNull &amp;&amp; tblC.AutoIncrement &amp;&amp; tblC.Unique</code>) is a hack, and I know it only works in some cases.</p> <p>I found the post <a href="https://stackoverflow.com/questions/1349357">How to determine a primary key for a table in SQL Server?</a> showing how to write an SQL Query to determine this, but can I tell somehow using the <code>DataTable</code> that I supply to the <code>DataGridView</code>?</p> <p>I also saw the post <a href="https://stackoverflow.com/questions/735140">C# Linq-to-SQL: Refectoring this Generic GetByID method</a> using Linq-to-SQL, but (though I try) I just don't understand that Linq jibberish.</p> <p>If determining the key is not supported, what would be the best approach? Two queries, one for schema and the other for the data, then go through the data using the schema collected?</p> <p><strong>EDIT:</strong> I noticed that when looking at the data table's schema using:</p> <pre><code>SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='Table1' </code></pre> <p>I am returned a <code>COLUMN_FLAGS</code> value. The table I am looking at shows a value of <code>18</code> for my <em>Primary Key</em> on this table. Is that a good test?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload