Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: SQL-Server .NET4
Hi,
I want to know column which has primary key defined in sql server database.
Following is my code
 
 
    SqlConnection con = new SqlConnection("Initial Catalog=Dbname; Data Source=MySqlServer; User=testuser; Password=pass123;");
 
    DataSet ds = new DataSet();
 
SqlCommand cmd = new SqlCommand("select * from TableName", con);
        cmd.CommandType = CommandType.Text;
 
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
 
        DataColumn[] columns;
        columns = ds.Tables[0].PrimaryKey;
 
        // Get the number of elements in the array.
         Response.Write("Column Count: " + columns.Length);
        for (int i = 0; i < columns.Length; i++)
        {
            Response.Write(columns[i].ColumnName + columns[i].DataType);
        }
In fact, i have defined one primary key on a column of
TableName
But my code returns zero count.
please correct me, if i am wrong and provide me alternative solution
thank is advance.
Posted 4-Feb-13 20:44pm
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

  Permalink  
Comments
Abhijit Parab at 5-Feb-13 2:21am
   
i think u have not understood my questiom. i want to know which table has primary key.i am fetching tables in dataset, from that dataset i want to know which table has primary key and count of the primary keys. i want logic in .net.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

I got the answer......
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
then
da.Fill(ds);
 
It worked......
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 George Jonsson 175
1 Kornfeld Eliyahu Peter 169
2 Zoltán Zörgő 139
3 PIEBALDconsult 130
4 OriginalGriff 120
0 OriginalGriff 6,165
1 DamithSL 4,658
2 Maciej Los 4,107
3 Kornfeld Eliyahu Peter 3,649
4 Sergey Alexandrovich Kryukov 3,342


Advertise | Privacy | Mobile
Web02 | 2.8.141220.1 | Last Updated 5 Feb 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100