Mangal Pandey
Mangal Pandey

Reputation: 109

Why datatable ignores initial spaces

Datatable does not take initial spaces, so when i insert it into database and retrieve it by select statement and display it on page using stringBuilder, Initial spaces are gone and text does not appear on screen as it is written in textbox

DataTable1.Rows[0][0]=TextBox1.Text;

This is how I insert into database

 public static void Insert(DataTable table)
        {
            StringBuilder Col = new StringBuilder();
            StringBuilder Val = new StringBuilder();
            string Query, finalVal;
            int i, j;
            int count = 0;
            int ColumnCount = table.Columns.Count;
            for (i = 0; i < ColumnCount; i++)
            {
                if (table.Rows.OfType<DataRow>().Any(r => !r.IsNull(table.Columns[i].ColumnName)))
                {
                    Col.Append(table.Columns[i].ColumnName);
                    Col.Append(",");
                    count++;
                }
            }
            Col.Remove(Col.Length - 1, 1);
            string[] columnName = Col.ToString().Split(',');
            foreach (DataRow r in table.Rows)
            {
                Val.Append(",(");
                for (j = 0; j < count; j++)
                {
                    if (r[columnName[j]] != null)
                    {
                        Val.Append("'" + r[columnName[j]] + "'");
                        Val.Append(",");
                    }
                    else
                    {
                        Val.Append("null,");
                    }
                }
                Val.Append(")");
                Val.Remove(Val.Length - 2, 1);

            }
            finalVal = Val.ToString().Substring(1);
            Query = "Insert into " + table.TableName + "(" + Col + ")" + "Values" + finalVal;
            EduDB.ExecuteNonQuery(Query);
        }

Upvotes: 0

Views: 81

Answers (1)

Animesh Anand
Animesh Anand

Reputation: 324

You must be trimming the string befor inserting into database. Please check that out

Upvotes: 2

Related Questions