Forum guidelines
How to obtain primary key of table
Posted By Abhijit Parab on 05 Feb 2013
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);

        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.

Re: How to obtain primary key of table
Posted By Santhosh Kumar Jayaraman on 05 Feb 2013   Accepted Answer
before fill add this line of code

da.MissingSchemaAction = MissingSchemaAction.AddWithKey

Thanks & Regards,SanthoshPlease mark this answer as accepted answer if it resolves your problem.
Aspose File APIs


Custom Software Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.