??xml version="1.0" encoding="utf-8" standalone="yes"?> BLL?nbsp; public void Update(DataTable dt) dal.Update(dt); DAL?/p>
public void Update(DataTable dt) adapter.InsertCommand = new SqlCommand("INSERT INTO dbo.t6( com_id ,usr_id ) VALUES( @com_id ,@usr_id)", conn); adapter.UpdateCommand = new SqlCommand("update t6 setwhereand usr_id", conn); adapter.DeleteCommand = new SqlCommand("delete from t6 whereand usr_id", conn); adapter.DeleteCommand.Parameters["@com_id"].SourceVersion = DataRowVersion.Original; adapter.Update(dt); 前台 public partial class DataTableUpdate : Form public BLL.Users Bu = new BLL.Users(); public string _UserId = ""; public DataTableUpdate() //H口加蝲 private void Form1_Load(object sender, EventArgs e) private void BindValue() //手动修改可以; 代码赋值需要用下面q句?br /> tb_UsrId.DataBindings[0].DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged; private void 保存_Click(object sender, EventArgs e) private void 删除_Click(object sender, EventArgs e) if (dataGridView1.CurrentCell == null) try private void 增加_Click(object sender, EventArgs e) private void 取消_Click(object sender, EventArgs e) 本节内容 数据添臌?/font>:说明如何创徏新行q将其添臌中?/p>
以下CZ演示?jin)如何通过调用 NewRow Ҏ(gu)来创建新行?/p>
DataRow workRow = workTable.NewRow(); 然后(zhn)可以用烦(ch)引或列名来操作新d的行Q如下例所C?/p>
workRow["CustLName"] = "Smith"; 在将数据插入新行后,Add Ҏ(gu)可用于将行添?span class="Apple-converted-space"> DataRowCollectionQ如以下代码所C?/p>
workTable.Rows.Add(workRow); (zhn)也可以通过传入值的数组Q类型化?span class="Apple-converted-space"> ObjectQ,调用 Add Ҏ(gu)来添加新行,如下例所C?/p>
workTable.Rows.Add(new Object[] {1, "Smith"}); 类型化?span class="Apple-converted-space"> Object 的值的数组传递到 Add Ҏ(gu)Q可在表内创建新行ƈ其列D|ؓ(f)对象数组中的倹{请注意Q数l中的g(x)Ҏ(gu)它们在表中出现的序相(h)与各列匹配?/p>
以下CZ十行添x(chng)建的 Customers 表中?/p>
DataRow workRow; 查看表中数据:说明如何讉K行中的数据,包括数据的原始版本和当前版本?/p>
DataTable 对象?span class="Apple-converted-space"> Select Ҏ(gu)q回一l与指定条g匚w?span class="Apple-converted-space"> DataRow 对象?strong>Select 采用{选表辑ּ、排序表辑ּ?span class="Apple-converted-space"> DataViewRowState 的可选参数。筛选表辑ּҎ(gu) DataColumn |例如 Select Ҏ(gu)Z DataViewRowState 定要查看或操作的行的版本。下表说明了(jin)可能?span class="Apple-converted-space"> DataViewRowState 枚D倹{?/p>
在下面的CZ中,DataSet 对象已经q筛选,q样Q?zhn)可以只用?span id="wmqeeuq" class="Apple-converted-space"> DataViewRowState 讄?span class="Apple-converted-space"> CurrentRows的行?/p>
DataRow[] currRows = workTable.Select(null, null, DataViewRowState.CurrentRows); Select Ҏ(gu)可用于返回具有不?span class="Apple-converted-space"> RowState 值或字段值的行。以下示例返回一个引用所有已删除行的 DataRow数组Qƈq回另一个引用所有已排序行(按照 CustLName 排序Q其?span class="Apple-converted-space"> CustID 列大?5Q的 DataRow 数组?/p>
// Retrieve all deleted rows. ~辑表中的数?/font>:说明如何修改行中的数据,包括挂v对行的更改,直至验证q接受了(jin)的更攏V?/p>
当?zhn)直接?span class="Apple-converted-space"> DataRow 中修改列值时Q?strong>DataRow ?x)?span class="Apple-converted-space"> Current?strong>Default ?span class="Apple-converted-space"> Original 行版本来理列倹{除q些行版本以外,BeginEdit?strong>EndEdit ?span class="Apple-converted-space"> CancelEdit Ҏ(gu)q(sh)用第四个行版本:(x)Proposed?/p>
在执行编辑操作(通过调用 BeginEdit 开始,q且通过使用 EndEdit ?span class="Apple-converted-space"> CancelEdit 或者通过调用AcceptChanges ?span class="Apple-converted-space"> RejectChanges l束Q的q程中,Proposed 行版本会(x)存在?/p>
在编辑操作过E中Q?zhn)可以通过计算 DataTable ?span class="Apple-converted-space"> ColumnChanged 事g中的 ProposedValue 来将验证逻辑应用于各列?strong>ColumnChanged 事g保存 DataColumnChangeEventArgsQ可保持Ҏ(gu)在更改的列和ProposedValue 的引用。计了(jin)值后Q可以对其进行修Ҏ(gu)取消~辑。编辑结束时Q行?span class="Apple-converted-space"> Proposed 状态中Ud?/p>
(zhn)可以通过调用 EndEdit 来确认编辑,也可以通过调用 CancelEdit 来取消编辑。请注意Q尽?span class="Apple-converted-space"> EndEdit 实已确认?zhn)所做的~辑Q但在调?span class="Apple-converted-space"> AcceptChanges 之前Q?strong>DataSet q没有实际接受更攏V另外请注意Q如果在EndEdit ?span class="Apple-converted-space"> CancelEdit ~辑l束之前调用 AcceptChangesQ编辑将?x)终止,q接?span class="Apple-converted-space"> Current ?span class="Apple-converted-space"> Original 行版本的 Proposed 行倹{调?span class="Apple-converted-space"> RejectChanges ?x)以同样的方式结束编辑,q放?span class="Apple-converted-space"> Current ?span class="Apple-converted-space"> Proposed 行版本。在调用 AcceptChanges ?span class="Apple-converted-space"> RejectChanges 之后调用 EndEdit ?span class="Apple-converted-space"> CancelEdit 不会(x)起作用,因ؓ(f)~辑已经l束?/p>
以下CZ演示?jin)如何?span id="wmqeeuq" class="Apple-converted-space"> BeginEdit ?span class="Apple-converted-space"> EndEdit ?span class="Apple-converted-space"> CancelEdit 一起用。本CZ也会(x)(g)?span class="Apple-converted-space"> ColumnChanged 事g中的 ProposedValueQƈ军_是否取消~辑?/p>
DataTable workTable = new DataTable(); 行状态与行版?/font>:提供有关行的不同状态的信息?/p>
每个 DataRow 对象都具?span class="Apple-converted-space"> RowState 属性,(zhn)可以检查此属性来定行的当前状态。下表给Z(jin)对各RowState 枚D值的要说明?/p>
对于已经使用 Remove Ҏ(gu)Q或是在使用 Delete Ҏ(gu)之后使用?span class="Apple-converted-space"> AcceptChanges Ҏ(gu)Q从DataRowCollection 中移除的行,也设|ؓ(f) Detached?/p> ?span class="Apple-converted-space"> DataSet?strong>DataTable ?span class="Apple-converted-space"> DataRow 上调?span class="Apple-converted-space"> AcceptChanges Ӟ?x)移除行状态ؓ(f) Deleted 的所有行。剩余的行会(x)被赋?span class="Apple-converted-space"> Unchanged 行状态,q且 Original 行版本中的g(x)改写?span class="Apple-converted-space"> Current 行版本倹{调?strong>RejectChanges Ӟ?x)移除行状态ؓ(f) Added 的所有行。剩余的行会(x)被赋?span class="Apple-converted-space"> Unchanged 的行状态,q且Current 行版本中的g(x)改写?span class="Apple-converted-space"> Original 行版本倹{?/p>
通过用列引用来传?span class="Apple-converted-space"> DataRowVersion 参数Q?zhn)可以查看行的不同行版本,如下例所C?/p>
DataRow custRow = custTable.Rows[0]; 下表l出?jin)?span id="wmqeeuq" class="Apple-converted-space"> DataRowVersion 枚D值的要说明?/p>
通过调用 HasVersion Ҏ(gu)q将 DataRowVersion 作ؓ(f)参数传递,(zhn)可以测?span class="Apple-converted-space"> DataRow 是否h特定的行版本。例如,在调?span class="Apple-converted-space"> AcceptChanges 之前Q?code class="ce">DataRow.HasVersion(DataRowVersion.Original) Ҏ(gu)d的行返?span class="Apple-converted-space"> false?/p>
例如Q以下代码示例显CZ(jin)表中所有已删除行的倹{已删除的行没有 Current 行版本,因此在访问列值时必须传?span class="Apple-converted-space"> DataRowVersion.Original?/p>
DataTable catTable = catDS.Tables["Categories"]; 从表中删除行:说明如何从表中移除行?/p>
在将 DataSet ?span class="Apple-converted-space"> DataTable ?span class="Apple-converted-space"> DataAdapter 和关pd数据源一起用时Q用 DataRow ?span class="Apple-converted-space"> Delete Ҏ(gu)U除行?strong>Delete Ҏ(gu)只是?span class="Apple-converted-space"> DataSet ?span class="Apple-converted-space"> DataTable 中将行标Cؓ(f) DeletedQ而不?x)移除它。?span class="Apple-converted-space"> DataAdapter 在遇到标Cؓ(f) Deleted 的行Ӟ?x)执行?span id="wmqeeuq" class="Apple-converted-space"> DeleteCommand 以在数据源中删除该行。然后,可以用AcceptChanges Ҏ(gu)怹U除该行。如果?span class="Apple-converted-space"> Remove 删除该行Q则该行从表中完全U除Q但DataAdapter 不会(x)在数据源中删除该行?/p>
DataRowCollection ?span class="Apple-converted-space"> Remove Ҏ(gu)采用 DataRow 作ؓ(f)参数Qƈ其从集合中U除Q如下例所C?/p>
workTable.Rows.Remove(workRow); 作ؓ(f)Ҏ(gu)Q以下示例演CZ(jin)如何调用 DataRow 上的 Delete Ҏ(gu)来将?span class="Apple-converted-space"> RowState 改ؓ(f) Deleted?/p>
workRow.Delete(); 如果行标记为删除,q且调用 DataTable 对象?span class="Apple-converted-space"> AcceptChanges Ҏ(gu)Q该行就?x)?span id="wmqeeuq" class="Apple-converted-space"> DataTable 中移除。相比之下,如果调用 RejectChangesQ行?span class="Apple-converted-space"> RowState ׃(x)恢复到被标记?span class="Apple-converted-space"> Deleted 之前的状态?/p>
d和读取行错误信息:说明如何按行插入错误信息Q以用于解决有关应用E序内行中数据的问题?/p>
DataTable workTable = new DataTable("Customers"); 接受或拒l对行的更改:说明如何接受或拒l对行的更改?/p>
如果 DataTable 上存在外键约束,使用 AcceptChanges ?span class="Apple-converted-space"> RejectChanges 接受或拒l的更改׃(x)Ҏ(gu)ForeignKeyConstraint.AcceptRejectRule 传播?span class="Apple-converted-space"> DataRow 的子行?/p>
以下CZ(g)查有错误的行Q在适用之处解决错误Q拒l无法解决错误的行。请注意Q对于解决的错误Q?strong>RowErrorg(x)重置为空字符ԌD?span class="Apple-converted-space"> HasErrors 属性设|ؓ(f) false。当解决或拒l了(jin)所有的有错误的行时Q就?x)调?strong>AcceptChanges 来接受对整个 DataTable 的所有更攏V?/p>
if (workTable.HasErrors) 处理 DataTable 事g:提供可用?span class="Apple-converted-space"> DataTable 的事件的相关信息Q包括修改列值和d或删除行时的事g?/p>
以下CZ创徏 4 个事Ӟ(x)OnColumnChanged?strong>OnColumnChanging?strong>OnRowChanged ?strong>OnRowChanging。这些事件中的每一个都在列或行更改时发生?/p>
workTable.ColumnChanged += new DataColumnChangeEventHandler(OnColumnChanged);
{
foreach (DataRow dr in dt.Rows)
{
if (dr.RowState == DataRowState.Deleted)
continue;
if (dr.RowState == DataRowState.Modified || dr.RowState == DataRowState.Added)
{
if (dr["usr_id"] == DBNull.Value)
{
throw new Exception("用户代码不能为空");
} }
}
}
{
SqlDataAdapter adapter = new SqlDataAdapter();
SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString);
conn.Open();
adapter.InsertCommand.CommandType = CommandType.Text;
adapter.InsertCommand.Parameters.Add("@com_id", SqlDbType.VarChar, 4, "com_id");
adapter.InsertCommand.Parameters.Add("@usr_id", SqlDbType.VarChar, 8, "usr_id");
adapter.UpdateCommand.CommandType = CommandType.Text;
adapter.UpdateCommand.Parameters.Add("@com_id", SqlDbType.VarChar, 4, "com_id");
adapter.UpdateCommand.Parameters.Add("@usr_id", SqlDbType.VarChar, 8, "usr_id");
adapter.UpdateCommand.Parameters.Add("@usr_id1", SqlDbType.VarChar, 8, "usr_id");
adapter.UpdateCommand.Parameters["@usr_id1"].SourceVersion = DataRowVersion.Original;
adapter.DeleteCommand.CommandType = CommandType.Text;
adapter.DeleteCommand.Parameters.Add("@com_id", SqlDbType.VarChar, 4, "com_id");
adapter.DeleteCommand.Parameters.Add("@usr_id", SqlDbType.VarChar, 8, "usr_id");
adapter.DeleteCommand.Parameters["@usr_id"].SourceVersion = DataRowVersion.Original;
}
{
public DataTable dtUsr = new DataTable();
public MOD.Users modObject = new MOD.Users();
{
InitializeComponent();
dataGridView1.AutoGenerateColumns = false;
}
{
dtUsr = Bu.GetList();
dataGridView1.DataSource = dtUsr;
BindValue();
}
{
tb_com_id.DataBindings.Add("Text", dataGridView1.DataSource, "com_id");
tb_UsrId.DataBindings.Add("Text", dataGridView1.DataSource, "usr_id");
}
{
foreach (DataRow dr in dtUsr.Rows)
{
dr.EndEdit();
}
try
{
Bu.Update(dtUsr);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
MessageBox.Show("保存成功Q?, "pȝ提示");
}
{
if (MessageBox.Show("(zhn)确认要删除用户Q? + tb_UsrName.Text.Trim()+" ?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
return;
return;
{
dataGridView1.Rows.Remove(dataGridView1.CurrentRow);
Bu.Update(dtUsr);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
MessageBox.Show("删除成功Q?, "pȝ提示");
}
{
DataRow dr = dtUsr.NewRow();
dr["usr_id"] = _UserId;
dtUsr.Rows.Add(dr);
dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0];
}
{
dtUsr.RejectChanges();
}
牛铁Q?a style="color: rgb(63,167,203); text-decoration: underline" >http://blog.csdn.net/fangxinggood/archive/2008/04/18/2304047.aspx
]]>
?span class="Apple-converted-space"> DataSet 中创?span class="Apple-converted-space"> DataTable 之后Q?zhn)执行的活动可以与使用数据库中的表时执行的zd相同。?zhn)可以d、查看、编辑和删除表中的数据;可以监视错误和事Ӟq且可以查询表中的数据。在修改 DataTable 中的数据Ӟ(zhn)也可以验证更改是否正确Qƈ军_是否以编E方式接受更Ҏ(gu)拒绝更改?/p>
在创?span class="Apple-converted-space"> DataTable q用列和约束定义其l构之后Q?zhn)可以新的数据行添至表中。要d新行Q可一个新变量声明?span class="Apple-converted-space"> DataRow cd。调?span class="Apple-converted-space"> NewRow Ҏ(gu)Ӟ返回新?span class="Apple-converted-space"> DataRow 对象。然后,DataTable ?x)根据表的结构?span id="wmqeeuq" class="Apple-converted-space"> DataColumnCollection 的定义创?span class="Apple-converted-space"> DataRow 对象?
workRow[1] = "Smith";
for (int i = 0; i <= 9; i++)
{
workRow = workTable.NewRow();
workRow[0] = i;
workRow[1] = "CustName" + i.ToString();
workTable.Rows.Add(workRow);
}
可以使用 DataTable ?span class="Apple-converted-space"> Rows ?span class="Apple-converted-space"> Columns 集合来访?span class="Apple-converted-space"> DataTable 中的内容。也可以Ҏ(gu)包括搜烦(ch)标准、排序顺序和行状态等特定标准Q?span class="Apple-converted-space"> DataTable.Select Ҏ(gu)q回 DataTable 中数据的子集。此外,用主键值搜索特定行Ӟq可使用 DataRowCollection ?span class="Apple-converted-space"> LastName = 'Smith'
。排序表辑ּ遵@用于为列排序的标?SQL U定Q例?span class="Apple-converted-space"> LastName ASC, FirstName ASC
。有关编写表辑ּ的规则,请参?strong>DataColumn cȝ 提示 如果(zhn)将?span class="Apple-converted-space"> DataTable ?span class="Apple-converted-space"> Select Ҏ(gu)执行多次调用Q可通过先ؓ(f) DataTable 创徏 DataView来提高性能。创?span class="Apple-converted-space"> DataView ?x)?f)表中的行~制索引。然后,Select Ҏ(gu)?x)用该索引Q这样将显著~短生成查询l果的时间。有关ؓ(f) DataTable 创徏 DataView 的信息,请参?a style="color: rgb(51,102,153); text-decoration: none" >创徏和?DataView?/blockquote>
成员名称
说明
CurrentRows
当前行,包括未更改的行、已d的行和已修改的行?/td>
Deleted
已删除的行?/td>
ModifiedCurrent
当前版本Q它是原始数据的修改版本Q请参阅ModifiedOriginalQ?/td>
ModifiedOriginal
所有已修改行的原始版本。?span class="Apple-converted-space"> ModifiedCurrent Ӟ当前版本可用?/td>
Added
新行?/td>
None
无?/td>
OriginalRows
原始行,包括未更改的行和已删除的行?/td>
Unchanged
未更改的行?/td>
if (currRows.Length < 1 )
Console.WriteLine("No Current Rows Found");
else
{
foreach (DataColumn myCol in workTable.Columns)
Console.Write("/t{0}", myCol.ColumnName);
Console.WriteLine("/tRowState");
foreach (DataRow myRow in currRows)
{
foreach (DataColumn myCol in workTable.Columns)
Console.Write("/t{0}", myRow[myCol]);
Console.WriteLine("/t" + myRow.RowState);
}
}
DataRow[] delRows = workTable.Select(null, null, DataViewRowState.Deleted);
// Retrieve rows where CustID > 5, and order by CustLName.
DataRow[] custRows = workTable.Select("CustID > 5", "CustLName ASC");
当?zhn)?span class="Apple-converted-space"> DataRow 中更改列值时Q所做更改会(x)立即|于行的 Current 状态中。然后,RowState ?x)设|ؓ(f)ModifiedQƈ使用 DataRow ?span class="Apple-converted-space"> AcceptChanges ?span class="Apple-converted-space"> RejectChanges Ҏ(gu)来接受或拒绝所做更攏V?strong>DataRowq提供了(jin)三种可用于在~辑行时行的状态挂L(fng)Ҏ(gu)。这些方法是 BeginEdit?strong>EndEdit ?span class="Apple-converted-space"> CancelEdit?
workTable.Columns.Add("LastName", typeof(String));
workTable.ColumnChanged += new DataColumnChangeEventHandler(OnColumnChanged);
DataRow workRow = workTable.NewRow();
workRow[0] = "Smith";
workTable.Rows.Add(workRow);
workRow.BeginEdit();
// Causes the ColumnChanged event to write a message and cancel the edit.
workRow[0] = "";
workRow.EndEdit();
// Displays "Smith, New".
Console.WriteLine("{0}, {1}", workRow[0], workRow.RowState);
protected static void OnColumnChanged(Object sender, DataColumnChangeEventArgs args)
{
if (args.Column.ColumnName == "LastName")
if (args.ProposedValue.ToString() == "")
{
Console.WriteLine("Last Name cannot be blank. Edit canceled.");
args.Row.CancelEdit();
}
}
ADO.NET 用行状态和版本理表中的行。行状态表C的状态。当修改行时Q行版本?x)维护存储于行中的|包括当前倹{原始值和默认倹{例如,修改?jin)某行中的一列后Q该行会(x)有一?span class="Apple-converted-space"> Modified 的行状态,q且?x)存在两个行版本Q?strong>CurrentQ包含当前行|(j)?span class="Apple-converted-space"> OriginalQ包含修改该列前的行|(j)?
RowState
说明
Unchanged
自上ơ调?span class="Apple-converted-space"> AcceptChanges 之后Q或?span class="Apple-converted-space"> DataAdapter.Fill 创徏?jin)行之后Q未做出qQ何更攏V?/td>
Added
已将行添臌中,但尚未调?span class="Apple-converted-space"> AcceptChanges?/td>
Modified
已更改了(jin)行的一些元素?/td>
Deleted
已将该行从表中删除,q且未调用 AcceptChanges?/td>
Detached
对于已经创徏但不属于M DataRowCollection 的行Q设|ؓ(f) Detached。新?span class="Apple-converted-space"> RowState讄?span class="Apple-converted-space"> Detached。通过调用 Add Ҏ(gu)新?span class="Apple-converted-space"> DataRow 添至 DataRowCollection 之后Q?strong>RowState 属性的D|ؓ(f) Added?
string custID = custRow["CustomerID", DataRowVersion.Original].ToString();
DataRowVersion
说明
Current
行的当前倹{如果是?span class="Apple-converted-space"> Deleted ?span class="Apple-converted-space"> RowState 的行Q则不存在此行版本?/td>
Default
特定行的默认行版本?strong>Added?strong>Modified ?span class="Apple-converted-space"> Unchanged 行的默认行版本是Current?strong>Deleted 行的默认行版本是 Original?strong>Detached 行的默认行版本是 Proposed?/td>
Original
行的原始倹{如果是?span class="Apple-converted-space"> Added ?span class="Apple-converted-space"> RowState 的行Q则不存在此行版本?/td>
Proposed
行的倹{在对行q行~辑操作期间Q或对于不属?span class="Apple-converted-space"> DataRowCollection 的行Q存在此行版本?/td>
DataRow[] delRows = catTable.Select(null, null, DataViewRowState.Deleted);
Console.WriteLine("Deleted rows:/n");
foreach (DataColumn catCol in catTable.Columns)
Console.Write(catCol.ColumnName + "/t");
Console.WriteLine();
foreach (DataRow delRow in delRows)
{
foreach (DataColumn catCol in catTable.Columns)
Console.Write(delRow[catCol, DataRowVersion.Original] + "/t");
Console.WriteLine();
}
用于?span class="Apple-converted-space"> DataTable 对象中删?span class="Apple-converted-space"> DataRow 对象的方法有两种Q?strong>DataRowCollection 对象?span class="Apple-converted-space"> Remove Ҏ(gu)?strong>DataRow 对象?span class="Apple-converted-space"> Delete Ҏ(gu)?strong>Remove Ҏ(gu)?span class="Apple-converted-space"> DataRowCollection 中删?span class="Apple-converted-space"> DataRowQ?span class="Apple-converted-space"> Delete Ҏ(gu)只将行标Cؓ(f)删除。当应用E序调用 AcceptChanges Ҏ(gu)Ӟ才会(x)发生实际的删除。通过使用 DeleteQ?zhn)可以在实际删除之前先以编E方式检查哪些行标记为删除。如果将行标Cؓ(f)删除Q其 RowState 属性会(x)讄?span class="Apple-converted-space"> Deleted?
注意 如果 DataRow ?span class="Apple-converted-space"> RowState ?span class="Apple-converted-space"> AddedQ则意味着已将其添臌中,然后其标记?strong>DeletedQ从表中U除?/blockquote>
Z(jin)避免在编?span class="Apple-converted-space"> DataTable 中的值时每次发生行错误都必须响应Q可错误信息添臌中,以便以后使用?strong>DataRow 对象通过对各行提?span class="Apple-converted-space"> RowError 属性来支持此功能。将数据添至 DataRow ?span class="Apple-converted-space"> RowError 属性会(x)?strong>DataRow ?span class="Apple-converted-space"> HasErrors 属性标Cؓ(f) true。如?span class="Apple-converted-space"> DataRow ?span class="Apple-converted-space"> DataTable 的组成部分,?span class="Apple-converted-space"> DataRow.HasErrors?span class="Apple-converted-space"> trueQ则 DataTable.HasErrors 属性也?span class="Apple-converted-space"> true。这也适用?span class="Apple-converted-space"> DataTable 所属的 DataSet。ؓ(f)错误做测试时Q可以检?span class="Apple-converted-space"> HasErrors 属性以定错误信息是否已添x(chng)有行。如?span class="Apple-converted-space"> HasErrors ?span class="Apple-converted-space"> trueQ则可?span class="Apple-converted-space"> DataTable ?strong>GetErrors Ҏ(gu)以便只返回和(g)查有错误的行Q如下例所C?
workTable.Columns.Add("CustID", typeof(Int32));
workTable.Columns.Add("Total", typeof(Double));
workTable.RowChanged += new DataRowChangeEventHandler(OnRowChanged);
for (int i = 0; i < 10; i++)
workTable.Rows.Add(new Object[] {i, i*100});
if (workTable.HasErrors)
{
Console.WriteLine("Errors In Table " + workTable.TableName);
foreach (DataRow myRow in workTable.GetErrors())
{
Console.WriteLine("CustID = " + myRow["CustID"]);
Console.WriteLine(" Error = " + myRow.RowError + "/n");
}
}
protected static void OnRowChanged(Object sender, DataRowChangeEventArgs args)
{
// Check for zero values.
if (args.Row["Total"].Equals(0D))
args.Row.RowError = "Total cannot be 0.";
}
在检验过?span class="Apple-converted-space"> DataTable 中的数据所做更改的准确性之后,可?span class="Apple-converted-space"> DataRow?strong>DataTable ?span class="Apple-converted-space"> DataSet ?strong>AcceptChanges Ҏ(gu)来接受更改,此方法会(x)?span class="Apple-converted-space"> Current 行D|ؓ(f) Original |q会(x)?span class="Apple-converted-space"> RowState 属性设|ؓ(f) Unchanged。接受或拒绝更改?x)清除所?span class="Apple-converted-space"> RowError 信息Qƈ?span class="Apple-converted-space"> HasErrors 属性设|ؓ(f) false。接受或拒绝更改q可以媄(jing)响在数据源中更新数据。有x(chng)多信息,请参?a style="color: rgb(51,102,153); text-decoration: none" >使用 DataAdapter ?DataSet 更新数据?/a>?
{
foreach (DataRow errRow in workTable.GetErrors())
{
if (errRow.RowError == "Total cannot exceed 1000.")
{
errRow["Total"] = 1000;
errRow.RowError = ""; // Clear the error.
}
else
errRow.RejectChanges();
}
}
workTable.AcceptChanges();
DataTable 对象提供一pd可由应用E序处理的事件。下表说明了(jin) DataTable 事g?
事g
说明
ColumnChanged
在值已成功插入列时发生?/td>
ColumnChanging
在已提交列值时发生?/td>
RowChanged
在已成功~辑表中的行后发生?/td>
RowChanging
当正在更改表中的行时发生?/td>
RowDeleted
在表中的某行已被标记?span class="Apple-converted-space"> Deleted 之后发生?/td>
RowDeleting
在表中的某行被标Cؓ(f) Deleted 之前发生?/td>
workTable.ColumnChanging += new DataColumnChangeEventHandler(OnColumnChanging);
workTable.RowChanged += new DataRowChangeEventHandler(OnRowChanged);
workTable.RowChanging += new DataRowChangeEventHandler(OnRowChanging);
protected static void OnColumnChanged(object sender, DataColumnChangeEventArgs args)
{
Console.Write(" ColumnChanged: ");
Console.Write(args.Column.ColumnName + " changed to '" + args.ProposedValue + "'/n");
}
protected static void OnColumnChanging(object sender, DataColumnChangeEventArgs args)
{
Console.Write("ColumnChanging: ");
Console.Write(args.Column.ColumnName + " equals '" + args.Row[args.Column] +
"', changing to '" + args.ProposedValue + "'/n");
}
protected static void OnRowChanging(object sender, DataRowChangeEventArgs args)
{
if (args.Action != DataRowAction.Nothing)
Console.WriteLine(" RowChanging: Action = " + args.Action + ", CustID = " + args.Row["CustID"]);
}
protected static void OnRowChanged(object sender, DataRowChangeEventArgs args)
{
if (args.Action != DataRowAction.Nothing)
Console.WriteLine(" RowChanged: Action = " + args.Action + ", CustID = " + args.Row["CustID"]);
}
]]>
当?/span>ComboboxSelectedValueSystem.Data.DataRowView在Combobox的DataSource不ؓ(f)I的情况?/strong>Q要么是没有?/span>ValueMemberSelectedValue。但有时即你对ValueMember :
Combobox1TextBox1ValueMemberCode-1Q?/strong>
q行上面的代码,H体初始化完毕后输出的结果如下:(x)
文本框显C的?#8220;System.Data.DataRowViewComboboxValueMemberValueMember ValueMemberDataSourceSelectedIndexChanged“System.Data.DataRowView解决Ҏ(gu)很简单:(x)只需DataSourceDisplayMemberValueMemberSelectedIndexChanged替换为SelectedValueChangedQ会(x)是什么效果呢Q试?jin)一下,没有报错Qƈ且窗体初始化完毕后显C的是预期的?。呵呵,又找C(jin)一U解x(chng)法。问题还没完Q请接着往(xin)下看Q?/span>
上面SelectedValueChanged的试验中QDataSource是在DisplayMemberValueMember前面的,如果攑ֈ它们两个后面呢?l箋(hu)试Q这ơ报错了(jin)——“未将对象引用到对象的CZ”Q对E序q行跟踪Q当执行完this.comboBox1.ValueMember = "Value"语句之后Q程序{C(jin)comboBox1_SelectedIndexChangedҎ(gu)Q在this.textBox1.Text = this.comboBox1.SelectedValue.ToString();语句处报错,SelectedValue的gؓ(f)I,因ؓ(f)此时q没有给DataSource赋|所以报q个错?/span>
现在可以ȝ?jin),当?span style="font-family: 新宋(hu)?>SelectedIndexChangedӞValueMember在DataSource前进行赋|当用SelectedValueChangedӞValueMember在DataSource后进行赋倹{?/strong>
q有一个问题很有意思,如下所C:(x)
this.comboBox1.DisplayMember = "Name";
this.comboBox1.ValueMember = "ValueError";
this.comboBox1.DataSource = table;
System.Data.DataRowViewQ然后我们对q三行代码的序做一下调_(d)如下Q?/span>
this.comboBox1.DataSource = table;
this.comboBox1.DisplayMember = "Name";
this.comboBox1.ValueMember = "ValueError";
上面ValueMember的g旧是错的Q但是对其赋值操作放C(jin)DataSource语句之后Q运行程序,在ValueMember赋D句处报错如下Q?span style="color: red">“无法l定到值成?/span>”?/span>
当指定了(jin)DataSource的值后再对ValueMember赋错Q如果此时赋D错的话,q行时就?x)报错,如果是在DataSource语句之前对ValueMember赋值则不会(x)报错Q大家在应用的时候一定要注意?/span>
?、几点要CQ?/p>
1 使用#using引用C# DLLQ而不?include.我就是想当然的用了(jin)后者,所以浪费了(jin)一上午的时_(d)
2 别忘?sh)(jin)using namespace CSLibQ?/p>
3 使用C++/clr语法Q采用正的讉K托管对象Q即Q用帽?#8216;^’Q而不是星?#8216;*’?br />
PSQ附上自己成功运行C++代码
#include "stdafx.h"
#include <iostream>
//#using "..\..\SFCSDLL.dll" //叛_目-->引用...Q添加新引用Q将DLLd到项目中Q可以不用此行代?/p>
using namespace std;
using namespace SFCSDLL;
int _tmain(int argc, _TCHAR* argv[])
{
Class1 ^c = gcnew Class1();
c->SFCSDLL_Create_Connection("127.0.0.1", 0, 0, 0, 0);
c->SFCSDLL_Get_DLLVersion();
c->SFCSDLL_Close_Connection();
cout<<"end...";
system("pause");
return 0;
}
|上最常见的做法是?/span>DataGridView?/span>RowPostPaint事g?/span>RowHeaderCell中绘制行P(x)
privatevoiddataGridView1_RowPostPaint(objectsender, DataGridViewRowPostPaintEventArgs e)
{
try
{
e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, new SolidBrush(Color.CadetBlue), e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + 5);
}
catch(Exception ex)
{
MessageBox.Show("d行号时发生错误,错误信息Q?/span>"+ex.Message, "操作p|");
}
}
但是q种Ҏ(gu)在大数据量的时候性能比较差,每次滚动数据都会(x)触发RowPostPaint事g?/span>
在VS2008里,也可以像Eclipse那样自动生成get 、setҎ(gu)?br />
下面是两个具体操作的Ҏ(gu)Q?br />
1、在~写的字D上单击右键----->重构------->装字段
2、在I白行处Q输?#8220;prop”再按Tab?/p>
关于VS2008或VS2005中数据库配置字符串的三种取法
VS2008建立FormE序?如果d数据源会(x)在配|文?app.config中自动写入连接字W串,q个字符串将?x)在你利用DataSet,SqlDataAparter,SqlConnection{控件时如媄(jing)随行地提CZ让去选择,或者是新徏字符丌Ӏ如果要用代码的方式取得q个字符串则有三U方式:(x)
app.config内容Q?/p>
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<appSettings>
<add key="connectionstring" value="Data Source=你的数据库器Q本机可用LocalHost,如果是EXPRESS开发版则必L.\SQLEXPRESS);Initial Catalog=数据库名?User ID=用户?Password=你自q密码 />
<add key="TemplatePATH" value="Template" />
</appSettings>
<connectionStrings>
<add name="SxzzManager.Properties.Settings.sxzzConnectionString"
connectionString="Data Source=你的数据库器;Initial Catalog=数据库名?User ID=sa;Password=你自q密码"
providerName="System.Data.SqlClient" />
<add name="TestConnectionString" connectionString="Data Source=你的数据库器;Initial Catalog=数据库名?User ID=sa;Password=你自q密码"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
说明Q?br />其中
??br /><appSettings>
<add key="connectionstring" value="Data Source=你的数据库器Q本机可用LocalHost,如果是EXPRESS开发版则必L.\SQLEXPRESS);Initial Catalog=数据库名?User ID=用户?Password=你自q密码 />
<add key="TemplatePATH" value="Template" />
</appSettings>
为手工所加?br />??br /> <add name="SxzzManager.Properties.Settings.sxzzConnectionString"
connectionString="Data Source=你的数据库器;Initial Catalog=数据库名?User ID=sa;Password=你自q密码"
providerName="System.Data.SqlClient" />
为在VS2008中添加数据源时自动生成的内容?br />??br /> <add name="TestConnectionString" connectionString="Data Source=你的数据库器;Initial Catalog=数据库名?User ID=sa;Password=你自q密码"
providerName="System.Data.SqlClient" />
为手工添加?br />要取得?》中所C的q接字符串用如下语句Q?br /> string ConString = System.Configuration.ConfigurationSettings.AppSettings["connectionstring"];
string ConString = System.Configuration.ConfigurationManager.AppSettings["connectionstring"];
要取得?》中所C的q接字符串有两种Ҏ(gu)
<1>: string constr = System.Configuration.ConfigurationManager.ConnectionStrings["SxzzManager.Properties.Settings.sxzzConnectionString"].ToString();
<2>: string constr = SxzzManager.Properties.Settings.Default["sxzzConnectionString"].ToString();//"其中"sxzzConnectionString"可以在VS2008中菜单=》项目=》属性=》设|=》名U?nbsp; 弹出的对话框中显C。其实就?SxzzManager.Properties.Settings.sxzzConnectionString"中最后一个点后面的字W串?br />要取得?》中所C的q接字符串则中能用?》中的一个字W串
string constr = ConfigurationManager.ConnectionStrings["TestConnectionString"].ToString();
string constr = ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString;
2、新建windows service工程后,pȝ自动生成一个Service1.cs文gQ默认是其设计视图。选择查看其代码,默认有构造函数、OnStart、OnStop三个函数Q如下图所C:(x)
3、新Z(jin)C# Windows服务之后Q还要设|该服务q行的周期,左侧的ToolBox中有两个timmerQ一个在lg下,一个在windows form下,可惜q两个都不能?/strong>Q我们要手工新徏一个timmerQƈ讄其属性和事g?/p>
- public WindowsServiceDemo()
- {
- InitializeComponent();
- System.Timers.Timer t = new System.Timers.Timer(1000);//实例化Timerc,讄间隔旉?0000毫秒Q?nbsp;
- t.Elapsed += new System.Timers.ElapsedEventHandler(TimeElapse);//到达旉的时候执行事Ӟ
- t.AutoReset = true;//讄是执行一ơ(falseQ还是一直执?true)Q?nbsp;
- t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事gQ?nbsp;
- }
- public void TimeElapse(object source, System.Timers.ElapsedEventArgs e)
- {
- //EventLog log = new EventLog();
- //log.Source = "我的应用E序";
- //log.WriteEntry("1U调用一?, EventLogEntryType.Information);
- FileStream fs = new FileStream(@"d:\timetick.txt", FileMode.OpenOrCreate, FileAccess.Write);
- StreamWriter m_streamWriter = new StreamWriter(fs);
- m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
- m_streamWriter.WriteLine("q了(jin)一U?nbsp;" + DateTime.Now.ToString() + "\n");
- m_streamWriter.Flush();
- m_streamWriter.Close();
- fs.Close();
- }
4、服务编写之后,q(sh)能由SCM(服务控制理?q行理Q需要给该服务添加装载器。在Service1.cs的设计视图,点击右键Q选择“d装蝲?#8221;Q系l默认就?x)添加ProjectInstaller.csq个cR?/p>
5、添加该cdQ在该类的设计视图上可看到serviceInstaller1和serviceProcessInstaller1Q分别设|其属性?/p>
讄serviceInstaller1的运行方式ؓ(f)手动或者自?/p>
讄serviceInstaller1的ServiceName,讄Z么,服务列表中就昄什?/p>
讄serviceProcessInstaller1的运行̎号ؓ(f)LocalSystem
6、编译该工程
7、用vs自带的命令行工具Q运行installutil ~译生成的exe
8、在pȝ的服务中可看到我们创建的服务?/p>
需要注意的?
如果你修改了(jin)q个服务Q\径没有变化的话是不需要重新注册服务的Q如果\径发生了(jin)变化Q需要先卸蝲q个服务InstallUtil.exe /u参数Q然后再重新安装q个服务Q不能直接安装。还有就是C# Windows服务是没有界面的Q不要企囄控制的输出方式来输出一些信息,你只能添加一个EventLogQ通过WriteEntry()来写日志?br />
MessageBox.Show("ok");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
试代码Q?br />
使用File.Create(@"C:testfile.txt")创徏试文本文gQ没调用CloseQ)(j)Ҏ(gu)释放?br />当执行上面的代码Ӟ?x)抛出异常,提示文g正在被用之cȝ异常信息?br />
针对在Window环境下,手动创徏TXT文档Qƈq行~辑Q不保存Q,以上判断代码不适用?/span>