为什么在dataGridView中更新的内容保存不上呢,高人给指点指点吧(在线等)
用datagridview绑定的数据表,想在表格中直接改数据,按书上例子做了,可是为什么总是保存不上呢。。。。。大家帮忙给看看吧。。。。
页面初始化:
private void Form2_Load(object sender, EventArgs e)
{
string sConn = "Data Source=AMINTA-EDF69EE4\\SQLEXPRESS;Initial Catalog=testa;Integrated Security=True;User ID=wx;Password=12345678 ";
string sql = "select * from tablea ";
sqlConnection1 = new SqlConnection(sConn);
sqlCommand1 = new SqlCommand(sql, sqlConnection1);
sqlCommand1.CommandText = "select aid from tablea order by aid ";
sqlDataAdapter1 = new SqlDataAdapter(sql, sqlConnection1);
DataSet dataSet1 = new DataSet();
sqlDataAdapter1.Fill(dataSet1, "tablea ");
dataGridView1.DataSource = dataSet1.Tables[ "tablea "];
}
保存按扭:
private void button1_Click(object sender, EventArgs e)
{
DataSet dataset1 = new DataSet();
try
{
this.dataGridView1.CurrentCell = this.dataGridView1[2, 2];
this.dataGridView1.BeginEdit(true);
DataSet changes = (DataSet)dataset1.GetChanges();
if (changes == null) //---总是运行到这里就报错了,好像changes的值一直都没有一样....是怎么回事啊........
{
return;
}
DataTable dt = changes.Tables[ "tablea "];
DataRow[] badrows = dt.GetErrors();
if (badrows.Length == 0)
{
int numrows = sqlDataAdapter1.Update(changes);
MessageBox.Show( "updated " + numrows + "rows ", "success ");
dataset1.AcceptChanges();
}
else
{
string errormsg = null;
foreach (DataRow row in badrows)
{
foreach (DataColumn col in row.GetColumnsInError())
{
errormsg += row.GetColumnError(col) + "\n ";
}
}
MessageBox.Show( "errors in data: " + errormsg, "please fix ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show( "error: " + ex.Message, "errors ", MessageBoxButtons.OK, MessageBoxIcon.Error);
dataset1.RejectChanges();
}
}
其它:
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
char newinteger;
dataGridView1.Rows[e.RowIndex].ErrorText = " ";
if (dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "aname " || dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "schoolname " || dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "telphone ")
{
if (char.TryParse(e.FormattedValue.ToString(),out newinteger)||newinteger.ToString() == " ")
//if (!int.TryParse(e.FormattedValue.ToString(), out newinteger) || newinteger < 0)
{
dataGridView1.Rows[e.RowIndex].ErrorText = "value must be a non-negative number ";
e.Cancel = true;
}
}
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.Rows[e.RowIndex].ErrorText = " ";
}
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
dataGridView1.Rows[e.RowIndex].ErrorText = "invalid input.please re-enter ";
e.Cancel = true;
}
[解决办法]
报什么错误?
[解决办法]
我知道了.你可能没有
if(!Page.IsPostBack )
看看