如何在C#中将数据从datagrid保存到SQL Server [英] How to save data from datagrid to SQL Server in C#
本文介绍了如何在C#中将数据从datagrid保存到SQL Server的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个datagrid包含14个空行。不,我想在sql server 2008中保存来自此数据网格的多条记录。
plzz ,ANyone可以帮助我。
解决方案
您好,
请查看下面的示例代码。我已经创建了一个数据表并与datagrid绑定,现在如果我在网格中添加一行,它将被添加到datatabel中。当用户点击保存按钮时,从数据表中读取数据并插入数据库。
使用系统;
使用 System.Collections.Generic;
使用 System.ComponentModel;
使用 System.Data;
使用 System.Drawing;
使用 System.Text;
使用 System.Windows.Forms;
命名空间 WindowsFormsApplication2
{
public 部分 类 Form1:表格
{
public Form1()
{
InitializeComponent();
}
DataTable dt = new DataTable();
private void button1_Click( object sender,EventArgs e)
{
MessageBox.Show(dt.Rows.Count.ToString());
// 循环从数据表中读取数据
foreach (DataRow dr in dt.Rows)
{
MessageBox.Show(dr [ 0 跨度>]的ToString()); // 第一个col值
MessageBox.Show(dr [ 1 跨度>]的ToString()); // 第二个col值
MessageBox.Show(dr [ 2 跨度>]的ToString()); // 第三列值
}
}
private void Form1_Load( object sender,EventArgs e)
{
dt.Columns.Add( 名称跨度>);
dt.Columns.Add( Number);
dt.Columns.Add( 年龄);
dataGridView1.DataSource = dt;
}
}
}
最好的问候
Muthuraja
i have a datagrid contains 14 empty rows. NOw, i want save the multiple record from this datagrid in the sql server 2008.
plzz, ANyone Can Help me.
解决方案
Hi,
Please go through the below sample code. I have created a datatable and bind with datagrid, Now if I add a row in the grid, it will get added into the datatabel. When user clicks save button, read the data from the data table and insert into the database.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } DataTable dt = new DataTable(); private void button1_Click(object sender, EventArgs e) { MessageBox.Show(dt.Rows.Count.ToString()); //loop to read the data from data table foreach (DataRow dr in dt.Rows) { MessageBox.Show(dr[0].ToString()); //First col value MessageBox.Show(dr[1].ToString()); //second col value MessageBox.Show(dr[2].ToString()); //third col value } } private void Form1_Load(object sender, EventArgs e) { dt.Columns.Add("Name"); dt.Columns.Add("Number"); dt.Columns.Add("Age"); dataGridView1.DataSource = dt; } } }
Best Regards
Muthuraja
这篇关于如何在C#中将数据从datagrid保存到SQL Server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文