gridview中的数据写入数据库(如何用gridview取出数据库里面的值并插入到另一个数据库呢)

本文目录
- 如何用gridview取出数据库里面的值并插入到另一个数据库呢
- 有什么办法能让我选中GRIDVIEW的一行后把这行的数据导入到新的数据库表里面,请给我一些具体的代码,谢谢
- asp.net问题!gridview用法:如何把girdview里的某条信息添加进自己的数据库
- 如何将从GridView中查询出来的数据插入数据库表中
- asp.net Gridview的数据怎么导入到数据库
- 在DataGridView中修改后的数据如何保存到数据库
- 怎么用数据库向gridview添加数据
如何用gridview取出数据库里面的值并插入到另一个数据库呢
1.逐行提取gridview的值。
2.gridview绑定的dataset或datatable(假设对象名为dt) 设置成全局变量。把
dataset或datatable中的数据,逐行添加到另一个数据库中。
datatable的行数:dt.Rows.Count
有什么办法能让我选中GRIDVIEW的一行后把这行的数据导入到新的数据库表里面,请给我一些具体的代码,谢谢
选中GRIDVIEW的一行:SelectedIndexChanged事件
使用SelectedIndexChanged事件,然后在该事件中执行导入操作。
如果每次点击都要执行导入数据库操作那么,要针对点击同一行这个情况再做处理,(如,每次点击行执行导入操作后,清空选中行)
asp.net问题!gridview用法:如何把girdview里的某条信息添加进自己的数据库
/// 《summary》
/// gridview行选择事件
/// 《/summary》
/// 《param name="sender"》《/param》
/// 《param name="e"》《/param》
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//获取选择行的单元格的值、以及选择行主键
//假如我前台页面绑定的字段名称是proID,那么这里就是Values.ToString();
string proID = GridView1.SelectedDataKey.Values.ToString();
string proName = GridView1.SelectedDataKey.Values.ToString();
//添加数据到数据库的方法,将proID 、proName 等等字段写入数据库的方法
}
如何将从GridView中查询出来的数据插入数据库表中
您好,gridview 的值不是数据库来的。。。。。
《ItemTemplate》
setHaoduan(《%#Eval("HaoDuan")%》);
《%#Eval("HaoDuan")%》
《/ItemTemplate》
后台:
public void setHaoduan(string haoduan)
{
string haoduans = haoduans+","+haoduan;
Session = haoduans;
}
string banzhus = Id.Split(’,’); //在把值取出来切割。
asp.net Gridview的数据怎么导入到数据库
这个是代码
protected void btnImport_Click(object sender, EventArgs e)
{
string filename = string.Empty;
try
{
filename = uploadxls(fileexcel);//上传xls文件
//ImportxlsToData(filename);//将xls文件的数据导入数据库
ImportxlsToData1(filename);
if (filename != string.Empty && System.IO.File.Exists(filename))
{
System.IO.File.Delete(filename);//删除上传的xls文件
}
}
catch (Exception ex)
{
Kit.ExcuteJS("alert(’" + ex.Message.Replace("’", "") + "’)");
}
}
/// 《summary》
/// 动态匹配数据库基表指标
/// 《/summary》
public void MatchTarget()
{
// 构造导入出错数据DataTable结构
DataTable errorDataTable = new DataTable();
errorDataTable.Columns.Add("出错行数", typeof(string));
SortedList《string, string》 list = new SortedList《string, string》();
char splitChars = ",".ToCharArray();
string sourceField = hdfSourceField.Value.TrimStart(splitChars);
string targetField = hdfTargetField.Value.TrimStart(splitChars);
if (sourceField.Length 》 0)
{
string sourceFieldList = sourceField.Split(splitChars);
string targetFieldList = targetField.Split(splitChars);
for (int i = 0; i 《 sourceFieldList.Length; i++)
{
list.Add(targetFieldList.Trim());
errorDataTable.Columns.Add(sourceFieldList, typeof(string));
}
}
if (list.Count 》 0)
{
ViewState = list;
ViewState = errorDataTable;
}
}
/// 《summary》
/// 获取DataTable的列名集合
/// 《/summary》
public List《string》 GetTableHead(DataTable dt)
{
List《string》 list = new List《string》();
for (int i = 0; i 《 dt.Columns.Count; i++)
{
list.Add(dt.Columns.ColumnName.Trim());
}
return list;
}
/// 《summary》
/// 从excel提取数据,并导入到数据库中(导入成功部分,提示失败的记录)
/// 《/summary》
/// 《param name="filename"》excel文件路径名《/param》
private void ImportxlsToData(string filename)
{
try
{
if (filename == string.Empty)
{
Kit.Alert("excel文件上传失败!");
return;
}
MatchTarget();
if (ViewState == null)
{
Kit.Alert("请输入原指标与目标指标对应关系!");
return;
}
string oledbconnstring = string.Empty;
oledbconnstring = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + filename + " ;Extended Properties=’Excel 8.0;IMEX=1;’";
OleDbConnection oledbconn = null;
OleDbDataAdapter oleadmaster = null;
DataTable m_tablename = new DataTable();
DataSet ds = new DataSet();
oledbconn = new OleDbConnection(oledbconnstring);
oledbconn.Open();
m_tablename = oledbconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (m_tablename != null && m_tablename.Rows.Count 》 0)
{
m_tablename.TableName = txtSheet.Text.Trim().ToString();
}
string sqlmaster;
sqlmaster = " select * from ";
oleadmaster = new OleDbDataAdapter(sqlmaster, oledbconn);
oleadmaster.Fill(ds, "XLData");
oleadmaster.Dispose();
oledbconn.Close();
oledbconn.Dispose();
// 首先验证填写的原指标是否在要导入的EXCEL表中存在
List《string》 columnNameList = GetTableHead(ds.Tables);
SortedList《string, string》 targetMatchList = (SortedList《string, string》)ViewState;
string messageInfo = string.Empty;
string targetColumnList = string.Empty;
foreach (KeyValuePair《string, string》 item in targetMatchList)
{
if (!IsExistsTarget(columnNameList, item.Value))
{
messageInfo += item.Value + ",";
}
targetColumnList += "," + item.Key;
}
if (messageInfo.Length 》 0)
{
messageInfo.TrimEnd(’,’);
messageInfo += "与要导入的EXCEL表格中的列名不同!";
Kit.Alert(messageInfo);
return;
}
// 导入数据
targetColumnList = targetColumnList.TrimStart(’,’);
int successRecord = 0;
int failRecord = 0;
// 构造导入出错数据DataTable
DataTable errorDataTable = (DataTable)ViewState;
foreach (DataRow dr in ds.Tables.Rows)
{
try
{
StringBuilder sb = new StringBuilder();
string sColumn = string.Empty;
string sValue = string.Empty;
sb.Append("insert into " + TableName + "(");
foreach (KeyValuePair《string, string》 item in targetMatchList)
{
sColumn += "," + item.Key;
if (dr.ToString().Trim().Length 》 0)
{
sValue += ",’" + dr.ToString().Trim().Replace("’", "’’") + "’";
}
else
{
sValue += ",null";
}
}
sColumn += ",OperatorId,OperateTime";
sValue += "," + OperatorId + ",getdate()";
sb.Append(sColumn.TrimStart(’,’) + ")");
sb.Append(" values(" + sValue.TrimStart(’,’) + ")");
int i = DbHelperSQL.ExecuteSql(sb.ToString());
if (i 》 0)
{
successRecord += 1;
string updateObjectSql = "update SDMS.Object set OperateTime=getdate() where EngName =’" + TableName.Split(’.’) + "’";
DbHelperSQL.ExecuteSql(updateObjectSql);
}
else
{
failRecord += 1;
}
}
catch
{
failRecord += 1;
DataRow row = errorDataTable.NewRow();
row = failRecord + 1;
for (int i = 0; i 《 errorDataTable.Columns.Count; i++)
{
if (i 》 0)
{
row;
}
}
errorDataTable.Rows.Add(row);
continue;
}
}
string info = "导入成功记录数为:" + successRecord + "。";
if (failRecord 》 0)
{
info += "导入失败记录数为:" + failRecord + "。";
}
Kit.Alert(info);
if (errorDataTable.Rows.Count 》 0)
{
gvUnImport.DataSource = errorDataTable;
gvUnImport.DataBind();
}
}
catch (Exception ex)
{
Kit.Alert(ex.ToString());
}
}
/// 《summary》
/// 从excel提取数据,并导入到数据库中(全部导入成功,失败则全部回滚)
/// 《/summary》
/// 《param name="filename"》excel文件路径名《/param》
private void ImportxlsToData1(string filename)
{
List《string》 sqlList = new List《string》();
try
{
if (filename == string.Empty)
{
Kit.Alert("excel文件上传失败!");
return;
}
MatchTarget();
if (ViewState == null)
{
Kit.Alert("请输入原指标与目标指标对应关系!");
return;
}
string oledbconnstring = string.Empty;
oledbconnstring = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + filename + " ;Extended Properties=’Excel 8.0;IMEX=1;’";
OleDbConnection oledbconn = null;
OleDbDataAdapter oleadmaster = null;
DataTable m_tablename = new DataTable();
DataSet ds = new DataSet();
oledbconn = new OleDbConnection(oledbconnstring);
oledbconn.Open();
m_tablename = oledbconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (m_tablename != null && m_tablename.Rows.Count 》 0)
{
m_tablename.TableName = txtSheet.Text.Trim().ToString();
}
string sqlmaster;
sqlmaster = " select * from ";
oleadmaster = new OleDbDataAdapter(sqlmaster, oledbconn);
oleadmaster.Fill(ds, "XLData");
oleadmaster.Dispose();
oledbconn.Close();
oledbconn.Dispose();
// 首先验证填写的原指标是否在要导入的EXCEL表中存在
List《string》 columnNameList = GetTableHead(ds.Tables);
SortedList《string, string》 targetMatchList = (SortedList《string, string》)ViewState;
string messageInfo = string.Empty;
string targetColumnList = string.Empty;
foreach (KeyValuePair《string, string》 item in targetMatchList)
{
if (!IsExistsTarget(columnNameList, item.Value))
{
messageInfo += item.Value + ",";
}
targetColumnList += "," + item.Key;
}
if (messageInfo.Length 》 0)
{
messageInfo.TrimEnd(’,’);
messageInfo += "与要导入的EXCEL表格中的列名不同!";
Kit.Alert(messageInfo);
return;
}
// 导入数据
targetColumnList = targetColumnList.TrimStart(’,’);
foreach (DataRow dr in ds.Tables.Rows)
{
StringBuilder sb = new StringBuilder();
string sColumn = string.Empty;
string sValue = string.Empty;
sb.Append("insert into " + TableName + "(");
foreach (KeyValuePair《string, string》 item in targetMatchList)
{
sColumn += "," + item.Key;
if (dr.ToString().Trim().Length 》 0)
{
sValue += ",’" + dr.ToString().Trim().Replace("’", "’’") + "’";
}
else
{
sValue += ",null";
}
}
sColumn += ",OperatorId,OperateTime";
sValue += "," + OperatorId + ",getdate()";
sb.Append(sColumn.TrimStart(’,’) + ")");
sb.Append(" values(" + sValue.TrimStart(’,’) + ")");
sqlList.Add(sb.ToString());
}
string updateObjectSql = "update SDMS.Object set OperateTime=getdate() where EngName =’" + TableName.Split(’.’) + "’";
sqlList.Add(updateObjectSql);
int errorRow ;
string errorInfo;
int count = DbHelperSQL.ExecuteSqlTran(sqlList, out errorRow, out errorInfo);
string info;
if (count 》 0)
{
info = "导入成功记录数为:" + (count-1) + "。";
}
else
{
info = "导入失败!失败记录行号为:" + errorRow + "。";
info += "失败记录原因为:" + errorInfo;
}
Kit.Alert(this, info, true, false);
}
catch (Exception ex)
{
Kit.Alert(ex.ToString());
}
}
/// 《summary》
/// 判断填写的原指标是否在要导入的EXCEL表中存在
/// 《/summary》
/// 《param name="columnNameList"》表头列名《/param》
/// 《param name="sourceTargetName"》用户填写的原指标名称《/param》
public bool IsExistsTarget(List《string》 columnNameList, string sourceTargetName)
{
foreach (string columnName in columnNameList)
{
if (sourceTargetName == columnName)
return true;
}
return false;
}
/// 《summary》
/// 上传excel文件
/// 《/summary》
/// 《param name="inputfile"》上传的控件名《/param》
private string uploadxls(System.Web.UI.HtmlControls.HtmlInputFile inputfile)
{
string orifilename = string.Empty;
string uploadfilepath = string.Empty;
string modifyfilename = string.Empty;
string fileextend = "";//文件扩展名
int filesize = 0;//文件大小
try
{
if (inputfile.Value != string.Empty)
{
//得到文件的大小
filesize = inputfile.PostedFile.ContentLength;
if (filesize == 0)
{
throw new Exception("导入的excel文件大小为0,请检查是否正确!");
}
//得到扩展名
fileextend = inputfile.Value.Substring(inputfile.Value.LastIndexOf(".") + 1);
if (fileextend.ToLower() != "xls")
{
throw new Exception("你选择的文件格式不正确,只能导入excel文件!");
}
//路径
uploadfilepath = Server.MapPath("~/Public/File");
//新文件名
modifyfilename = System.Guid.NewGuid().ToString();
modifyfilename += "." + inputfile.Value.Substring(inputfile.Value.LastIndexOf(".") + 1);
//判定是否有该目录
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(uploadfilepath);
if (!dir.Exists)
{
dir.Create();
}
orifilename = uploadfilepath + "\\" + modifyfilename;
//假如存在,删除文件
if (File.Exists(orifilename))
{
File.Delete(orifilename);
}
// 上传文件
inputfile.PostedFile.SaveAs(orifilename);
}
else
{
throw new Exception("请选择要导入的excel文件!");
}
}
catch (Exception ex)
{
throw ex;
}
return orifilename;
}
在DataGridView中修改后的数据如何保存到数据库
namespace DategridviewToSQL
{
public partial class Form1 : Form
{
private DataTable DT = new DataTable();
private SqlDataAdapter SDA = new SqlDataAdapter();
private Boolean isUpdate = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
load();
}
private void load()
{
SqlConnection conn = new SqlConnection(@"server = (local)\SQL2005;Integrated Security = true;" + "DataBase = test1");
SqlCommand SCD = new SqlCommand("select * from aaa ", conn);
SDA.SelectCommand = SCD;
SDA.Fill(DT);
dataGridView1.DataSource = DT;
}
private void button1_Click(object sender, EventArgs e)
{
if (isUpdate)
{
try
{
SqlCommandBuilder SCB = new SqlCommandBuilder(SDA);
SDA.Update(DT);
isUpdate = false;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
return;
}
MessageBox.Show("更新成功! ");
}
else
{
MessageBox.Show("没有更新内容! ");
}
for (int i = 0; i 《 DT.Rows.Count; i++)
for (int j = 0; j 《 DT.Columns.Count; j++ )
{
dataGridView1.Style.BackColor = Color.White;
}
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
isUpdate = true;
dataGridView1.Style.BackColor = Color.Blue;
}
自己写的一个小实例,连接一个数据库,取了一个表显示,里面的链接语句可以根据你自己的数据库修改。试试看
怎么用数据库向gridview添加数据
GridView中的数据要写入到数据库,用代码方式实现: 1,ADO.net连接数据 2,Insert数据到数据库 3,Select数据绑定到GridView,搞定。 具体代码要自己写了

更多文章:
diverse culture课件(英语邮件范例:旅游英语怎么表达)
2026年3月2日 00:30
字符串全排列(abcdefgh由这八个字符构成的全排列字符串,要求不能出现以下子串:abc ,de,gh.求能有)
2026年3月9日 23:15
javascript 字符串转数字(如何用JavaScript对字符串进行解析并计算出结果)
2025年5月28日 03:00
如何使用u盘安装linux系统(怎么用u盘安装过linux详细步骤!)
2026年1月10日 17:45
domestic abuse only happens(帮我翻译一下这段英语 谢谢啦 ~!!!!!!!!!!!!!!!!!!!)
2026年4月17日 08:45
settimeout怎么停止(window.setTimeout 停止 取消)
2025年6月10日 15:15
word如何设置图片居中?网页中如何用HTML/CSS实现文字居中于图片
2025年6月28日 16:15
php教程视频谁的好(哪里的php视频教程不错我想自学php)
2026年5月11日 14:15
unity 命名空间(为什么unity无法将脚本添加到空的对象)
2026年1月21日 21:00
decimal在python(python字符的精度不够,用什么填充)
2026年8月13日 02:15
禁止iframe嵌套(https页面iframe嵌套http的页面,弹出警告,怎么解决)
2026年5月5日 09:45












