利用C#在做应用时偶然间发现的关于DataGridView的问题。下面是一个Demo。
窗口界面如图:后台代码如下:using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlDataAdapter sqlDA;
DataTable dt;
public Form1()
{
InitializeComponent();
} private void btnModify_Click(object sender, EventArgs e)
{
dgv.CurrentCell.Value = "123";
DataRowView drv = (DataRowView)dgv.CurrentRow.DataBoundItem;
MessageBox.Show(drv.Row.RowState.ToString());
} private void Form1_Load(object sender, EventArgs e)
{
string strConn = "Data Source=192.168.1.110;Initial Catalog=GD-Pipe;Persist Security Info=True;User ID=sa;Password=123";
sqlDA = new SqlDataAdapter("SELECT * FROM ModelType", new SqlConnection(strConn));
SqlCommandBuilder sqlCB = new SqlCommandBuilder(sqlDA);
dt = new DataTable();
sqlDA.Fill(dt); dgv.DataSource = dt;
}
}
}点击“修改”按钮后,DataGridView和绑定在上面的DataTable中的所对应的值都改变了,可是DataTable中的RowState依然是Unchanged,这是怎么回事呢?
环境:VS2010,SQL2008
DataGridView
窗口界面如图:后台代码如下:using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlDataAdapter sqlDA;
DataTable dt;
public Form1()
{
InitializeComponent();
} private void btnModify_Click(object sender, EventArgs e)
{
dgv.CurrentCell.Value = "123";
DataRowView drv = (DataRowView)dgv.CurrentRow.DataBoundItem;
MessageBox.Show(drv.Row.RowState.ToString());
} private void Form1_Load(object sender, EventArgs e)
{
string strConn = "Data Source=192.168.1.110;Initial Catalog=GD-Pipe;Persist Security Info=True;User ID=sa;Password=123";
sqlDA = new SqlDataAdapter("SELECT * FROM ModelType", new SqlConnection(strConn));
SqlCommandBuilder sqlCB = new SqlCommandBuilder(sqlDA);
dt = new DataTable();
sqlDA.Fill(dt); dgv.DataSource = dt;
}
}
}点击“修改”按钮后,DataGridView和绑定在上面的DataTable中的所对应的值都改变了,可是DataTable中的RowState依然是Unchanged,这是怎么回事呢?
环境:VS2010,SQL2008
DataGridView
我还发现在首次修改某条记录时会是Unchanged,在第二次修改时则变为Modified了。
你这还是属于还在编辑中吧。
现在还有一个问题,就是DataTable中的数据值的发生改变,是不是其RowState也会随之更改?现在看来问题的答案是否定的,因为修改DataGridView中的值后,DataTable中的值也修改了,但是其RowState并为发生改变。我想这可能跟DataSet中的DataRelation有关系,MSDN上RowState的解释为“获取与该行和 DataRowCollection 的关系相关的当前状态”。到底是什么原因,我现在就没时间去看了,希望有知道的大神能给解释一下。
好了,结贴。
{
dgv.BeginEdit(false);
dgv.CurrentCell.Value = "123";
dgv.EndEdit();
MessageBox.Show(dgv.IsCurrentRowDirty.ToString());
}
private void btnModify_Click(object sender, EventArgs e)
{
if (dgv.CurrentCell != null)
{
dgv.CurrentCell.Value = "123";
DataRowView drv = dgv.CurrentCell.OwningRow.DataBoundItem as DataRowView;
//这句是重点
drv.Row.EndEdit();
}
}