简体   繁体   中英

Why do I have many spaces after each data in a cell in my datagridview cell rows data from database?

I inserted data into my SQL Server database Leyte :

using (SqlConnection myConnection = new SqlConnection(con))
{
    myConnection.Open();

    SqlDataAdapter adapt = new SqlDataAdapter("select prov_name from tbl_CoopList", con);

    DataTable dt = new DataTable();
    adapt.Fill(dt);

    dgv_CoopList.DataSource = dt;

    myConnection.Close();
}

The problem was at runtime, in datagridview, when I double click the cell it has many spaces like:

 "Leyte (and a lot of spaces)".

I have been trying to solve my problem in how to center my data texts for each cell even though i have this code :

dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

I want the result to be the same as what I have inserted in my SQL Server database. How can I possibly erase all the blank spaces so it will be centered automatically.

I'm reasonably certain it's because you've declared your database column type as CHAR (or NCHAR) rather than VARCHAR (or NVARCHAR)

CHAR is a fixed length data type. If you declare a column as being CHAR(10) and then insert the value foobar (6 characters) and then query it back, you will get everything between the arrows:

>foobar    <

This is your six characters of foobar plus 4 spaces to make it up to ten characters for the CHAR(10)

Convert your database columns to VARCHAR (or NVARCHAR)

this.DataGridView.Columns[2].DefaultCellStyle.WrapMode = DataGridViewTriState.True;         
this.DataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;         
this.DataGridView.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

Hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM