开发者

get column names from a table where one of the column name is a key word

开发者 https://www.devze.com 2022-12-28 09:07 出处:网络
Im using c# .net windows form application. I have created a database which has many tables. In one of the tables I have entered data. In this table I have 4 columns named key, name,age,value. Here the

Im using c# .net windows form application. I have created a database which has many tables. In one of the tables I have entered data. In this table I have 4 columns named key, name,age,value. Here the name "key" of the first column is a key word. Now I am trying to get these column names into a combo box. I am unable to get the name "key".

It works for "key" when I use this code:

private void comboseccolumn_SelectedIndexChanged(object sender, EventArgs e)
{
    string dbname = combodatabase.SelectedItem.ToString();
    string path = @"Data Source=" + textBox1.Text + ";Initial Catalog=" + dbname + ";Integrated Security=SSPI";
    //string path=@"Data Source=SYED-PC\SQLEXPRESS;Initial Catalog=resources;Integrated Security=SSPI";
    SqlConnection con = new SqlConnection(path);
    string tablename = comboBox2.SelectedItem.ToString();
    //string query= "Select * from" +tablename+;
    //SqlDataAdapter adp = ne开发者_运维百科w SqlDataAdapter(" Select [Key] ,value from " + tablename, con);
    SqlDataAdapter adp = new SqlDataAdapter(" Select [" + combofirstcolumn.SelectedItem.ToString() + "]," + comboseccolumn.SelectedItem.ToString() + "\t from " + tablename, con);
    DataTable dt = new DataTable();
    adp.Fill(dt);

    dataGridView1.DataSource = dt;
}

This is beacuse I am using "[" in the select query. But it wont work for non keys. Or if I remove the "[" it is not working for key . Please suggest me so that I can get both key as well as nonkey column names.


Just enclosed them in square bracket:

select [key] from tbl

Or if you want your code to be ANSI-compliant, use double quote:

select "key" from tbl

Try this if this will work:

SqlDataAdapter adp = new SqlDataAdapter(" Select \"" + combofirstcolumn.SelectedItem.ToString() + "\"," + comboseccolumn.SelectedItem.ToString() + "\t from " + tablename, con);


Value is also a keyword in MSSQL. I would have thought that you would have to wrap this in [] too.


Try using Alias for the "key" column.

For E.g: Select Key as Keyword ,value as KeywordValue ...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号