Hello,
I am trying to upload .CSV file in gridview of asp.net i am successfully upload that file in gridview now i want to store that uploaded gridview data in sql server on button click.
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Khargesh RajputPosted Jan 28, 2015, 5:52 AM
after adding row in dt
Vishnu BhangalePosted Jan 28, 2015, 5:27 AM
i try it but in dt it shows only header row and data is come in to dt
Khargesh RajputPosted Jan 27, 2015, 10:44 PM
Vishnu BhangalePosted Jan 27, 2015, 7:56 AM
Vishnu BhangalePosted Jan 27, 2015, 7:47 AM
I already try this but give error:
Input string was not in a correct format.
My DB Table structure is like
UserName varchar(50),
Email varchar(50),
Mobile int
Khargesh RajputPosted Jan 27, 2015, 6:42 AM
{
string UserName = row.Cells[0].Text;
string Email = row.Cells[1].Text;
int Mobile = int.Parse(row.Cells[2].Text);
dt.Rows.Add(UserName, Email, Mobile);
}
Vishnu BhangalePosted Jan 27, 2015, 6:12 AM
In my CSV file contain 3 column UserName,Email,Mobile
protected void btn_Add_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3]
{ new DataColumn("UserName", typeof(string)),
new DataColumn("Email", typeof(string)),
new DataColumn("Mobile",typeof(int))
});
foreach (GridViewRow row in gridview1.Rows)
{
string UserName = row.Cells[1].Text;
string Email = row.Cells[2].Text;
int Mobile = int.Parse(row.Cells[3].Text);
dt.Rows.Add(UserName, Email, Mobile);
}
if (dt.Rows.Count > 0)
{
string consString = ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.CSV";
//[OPTIONAL]: Map the DataTable columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("UserName", "UserName");
sqlBulkCopy.ColumnMappings.Add("Email", "Email");
sqlBulkCopy.ColumnMappings.Add("Mobile", "Mobile");
con.Open();
sqlBulkCopy.WriteToServer(dt);
con.Close();
}
}
}
}
Khargesh RajputPosted Jan 27, 2015, 5:54 AM
you have to match the columns in csv and database
Vishnu BhangalePosted Jan 27, 2015, 5:22 AM
Specified argument was out of the range of valid values.
I try to solve it but not get any solution..
Khargesh RajputPosted Jan 27, 2015, 3:09 AM
or insert each row to sql db
http://www.aspsnippets.com/Articles/Using-SqlBulkCopy-to-insert-bulk-data-from-GridView-to-database-in-ASPNet.aspx
http://www.c-sharpcorner.com/UploadFile/0c1bb2/insert-bulk-records-into-database-using-Asp-Net-C-Sharp/
http://aspforums.net/Threads/155716/Bulk-Insert-Data-from-GridView-Rows-into-Database-in-ASPNet/