C# datagridview输入数据后,怎样通过保存修改按钮把数据保存到数据库中,要源代码

C# datagridview输入数据后,怎样通过保存修改按钮把数据保存到数据库中,要源代码,第1张

string a = thisGridView2DataKeys[eRowIndex][0]ToString();

string str = ((TextBox)thisGridView2Rows[eRowIndex]Cells[0]Controls[0])Text;

string ds = ((TextBox)thisGridView2Rows[eRowIndex]Cells[1]Controls[0])Text;

SqlConnection con = new SqlConnection("Data Source=;Initial Catalog=Test;Integrated Security=True");

conOpen();

SqlCommand cmd=new SqlCommand("update T1 set T_title='"+str+"' ,T_date='"+ds+"' where T_id='"+a+"'",con);

if (ConvertToInt32(cmdExecuteNonQuery()) > 0)

{

ResponseWrite("更新成功");

}

else

ResponseWrite("更新失败");

bind();

}

using System;

using SystemCollectionsGeneric;

using SystemComponentModel;

using SystemData;

using SystemDrawing;

using SystemText;

using SystemWindowsForms;

using SystemDataSqlClient;

namespace winform1

{

public partial class Form3 : Form

{

public Form3()

{

InitializeComponent();

}

private SqlConnection cn;

private SqlCommandBuilder builder;

private SqlDataAdapter da;

private DataSet ds;

//查找事件,点击页面“查找”,

private void butSearch_Click(object sender, EventArgs e)

{

cn = new SqlConnection("server=;database=test;uid=sa;pwd=123");

cnOpen();

ds = new DataSet();

SqlCommand cmd = new SqlCommand("select from Test", cn);

da = new SqlDataAdapter(cmd);

//添加必要的列和主键信息以守成架构

daMissingSchemaAction = MissingSchemaActionAddWithKey;

builder = new SqlCommandBuilder(da);

daFill(ds, "Test");//表名一定不能少哦。。。

thisdataGridView1DataSource = dsTables[0]DefaultView;

}

//更新事件

private void butUpdate_Click(object sender, EventArgs e)

{

int row = daUpdate(ds, "Test");

MessageBoxShow("更新完成" + row + builderGetUpdateCommand()CommandText);

}

//插入新记录事件

private void btnInsert_Click(object sender, EventArgs e)

{

DataRow findRow = dsTables[0]RowsFind("1111");//获取包含指定主键值的行

if (findRow != null)

{

MessageBoxShow("已有这个记录");

return;

}

DataRow dr = thisdsTables[0]NewRow();

dr["StuId"] = thistexStuIdText;

dr["StuName"] = thistexStuNameText;

dr["StuScore "] = "100";

thisdsTables[0]RowsAdd(dr);

int row = daUpdate(ds, "Test");

MessageBoxShow("添加完成" + row + builderGetInsertCommand()CommandText);

}

//删除选中记录

private void btnDelete_Click(object sender, EventArgs e)

{

dsTables[0]Rows[thisdataGridView1CurrentRowIndex]Delete();

int row = daUpdate(ds, "Test");

MessageBoxShow("删除完成" + row + builderGetDeleteCommand()CommandText);

}

//查询事件

private void btnSearch_Click(object sender, EventArgs e)

{

SqlCommand cmd = new SqlCommand("select from Test where StuId=@StuId", cn);

cmdParametersAdd("@StuId", SqlDbTypeChar, 8);

cmdParameters["@StuId"]Value = thistexIdText;

da = new SqlDataAdapter(cmd);

dsClear();

daFill(ds, "Test");

thisdataGridView1DataSource = dsTables[0]DefaultView;

}

}

}

dimsqlconnection1assqlclientsqlconnectiondimstrconnectasstring="datasource=127001;initialcatalog=cade;userid=sa;password=12345;"sqlconnection1=newsystemdatasqlclientsqlconnection(strconnect)'加上下面几行代码就可以了dimdaasnewsqldataadapter("selectfrom表",sqlconnection1)'这里的链接默认就是打开的dimdtasnewdatatabledafill(dt)datagridview1datasource=dt

isUpdate

=

false;}catch

(System

Exception

ex){

MessageBox

Show(exToString());return;}MessageBoxShow("更新成功!

");}else{MessageBoxShow("没有更新内容!

");}for

(int

i

=

0;

i

<

DTRowsCount;

i++)

dataGridView

1[eColumnIndex,eRowIndex]StyleBackColor

=

ColorBlue;}自己写的一个小实例,连接一个数据库,取了一个表显示,里面的链接语句可以根据你自己的数据库修改。试试看

DataTable dt=new DataTable();

//DataTable dt = CommonGetDgvToTable(ddvDBServertb);

DataTableToList<DBServertbModel> dlist = new DataTableToList<DBServertbModel>(dt);

for (int i = 0; i < dtRowsCount; i++)

{

model_tp = dlistToList()[i];

if (ValiData() == false)

{

continue;

}

Guid gui = SystemGuidNewGuid();

if (ddvDBServertbRows[i]DataBoundItem == null)//第一次添加数据

{

model_tpDBServertb_id = guiToString()ToUpper();

//bllAdd(model_tp);

}

else

{

string state = ((DataRowView)(ddvDBServertbRows[i]DataBoundItem))RowRowStateToString();

switch (state)

{

case "Detached":

model_tpDBServertb_id = guiToString()ToUpper();

bllAdd(model_tp);

break;

case "Added":

model_tpDBServertb_id = guiToString()ToUpper();

bllAdd(model_tp);

break;

//case "Modified": //失去焦点方法和RowState方法冲突,待优化

// bllUpdate(model_tp);

//break;

default:

bllUpdate(model_tp);

break;

}

}

}

这个思路是这样的,我有实体层,DAL,BLL。这个实例主要实现在界面上输入要修改的内容,然后点击保存按钮保存到数据库里面。不过我用的是Winform中的datagridview。希望你能变通成你能用的。

获取datagridview单元格修改后的值,然后用这个值去更新数据库就可以了,下面上代码

try

            {

                SqlConnection scon = new SqlConnection("数据库连接字");

                sconOpen();

                SqlCommand scmd;

                for (int i = 0; i < dataGridView1RowsCount; i++)

                {

                    string id = dataGridView1Rows[i]Cells["id"]EditedFormattedValueToString();

                    string name = dataGridView1Rows[i]Cells["name"]EditedFormattedValueToString();

                    string age = dataGridView1Rows[i]Cells["age"]EditedFormattedValueToString();

                    string address = dataGridView1Rows[i]Cells["address"]EditedFormattedValueToString();

                    string scmdStr = "update studentInfo set name='" + name + "',age='" + age + "',address='" + address + "' where id ='" + id + "'";

                    scmd = new SqlCommand(scmdStr, scon);

                    scmdExecuteNonQuery();

                }

                sconClose();

            }

            catch(Exception ex)

            {

                MessageBoxShow(exToString());

            }

首先将表读取到DataSet

用DataGridView绑定数据源

在 datagridview中直接修改字段的值后,用

SqlDataAdapter的Update方法更新

DataSet即可!

以上就是关于C# datagridview输入数据后,怎样通过保存修改按钮把数据保存到数据库中,要源代码全部的内容,包括:C# datagridview输入数据后,怎样通过保存修改按钮把数据保存到数据库中,要源代码、c# datagridview,怎么保存修改或新增数据到数据库、在vb.net中datagridview上修改的数据如何保存到sql数据库中等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/sjk/9704758.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-01
下一篇2023-05-01

发表评论

登录后才能评论

评论列表(0条)

    保存