user3786134
user3786134

Reputation: 361

how to concatenate different column of sql and showing it in datagridview c#

I have SQL table which has several columns I want to concatenate some of the columns and edit them and then show them in a datagrid view I am facing a problem here witch is I am retrieving data from sql but i can not save them in a variable too manipulate the data and then inserting it in the datagrid , I thought of putting a data in a datagrid and then manipulate the hidden datagridview data s and then insert the new variables in new datagrid view but is there an easier way for doing this like the one in the php that we could fetch the returned data in an array and then using the variables or I should go just like the way i described.

Upvotes: 1

Views: 1626

Answers (2)

MediSoft
MediSoft

Reputation: 161

you can use the sql statement to concat the column

select column1+' '+column2 from table       - in SQl server 
select column1|| ' '|| column2 from table   - in Oracle 
select concat(column1, concat(' ', column2)) from table    -in Mysql

and use a datasource bind to bind to datagridview

Upvotes: 1

mybirthname
mybirthname

Reputation: 18137

SqlConnection conn = new SqlConnection("YourConnectionString");

conn.Open();

SqlCommand cmd = new SqlCommand("Query for fetching your data", conn);
//cmd.Parameters.AddWithValue("@P1", p1Value); if the query need parameters to prevent sql injection.

DataSet resultDst = new DataSet();

using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
    dapter.Fill(resultDst, "TableName");
}

conn.Close();

foreach(DataRow row in resultDst.Tables[0].Rows)
{
   //manuipulate the data if needed
   //row["ColumnName"] = some value;
}


//if this is winforms you need only datagrid dataSource property to be set, if you are using asp.net //you need to databind after that.

dataGridView1.DataSource = resultDst.Tables[0];

From your exlanation you need something like this.

Upvotes: 0

Related Questions