user3377879
user3377879

Reputation: 43

how to change datatype of a column in data table through code?

I want to change datatype of column name called "FaxNo" from int to numeric.. I tried with this code..

 private void btnOK_Click(object sender, EventArgs e)
    {
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
        string s = "ALTER TABLE Add_Information ALTER COLUMN FaxNo numeric(18,0)";

            con.Open();
            SqlCommand cmd = new SqlCommand(s, con);
            if (cmd.ExecuteNonQuery() >= 1)
            {
                MessageBox.Show("Successfully updaed");
            }
            else
            {
                MessageBox.Show("Not done");
            }
            con.Close();     
    }

My table name is Add_Information It is showing message as Not done. Help me out to resolve this problem.

Upvotes: 1

Views: 571

Answers (1)

Neel
Neel

Reputation: 11721

I guess You cannot change the DataType of a DataColumn after populating it with data. It's not a read-only property, but you will receive an exception at runtime if you attempt to change it after it already has data.

According to msdn document linked below

http://msdn.microsoft.com/en-us/library/system.data.datacolumn.datatype.aspx:

An exception is generated when changing this property after the column has begun storing data.

So you will have to either ensure the correct column types in the beginning (if possible), or create a new DataTable specifically for the import and copy data from the original DataTable.

Upvotes: 1

Related Questions