I have a gridview with a delete button. I've added a messagebox with an 'are you sure' yes/no. The row of data is deleted fine when you click yes, but the gridview data disappears if you click no.
Here's the code for the delete button click:
private void gvOrderLines_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int intOrderID = 0;
if (e.RowIndex < 0 || e.ColumnIndex != gvOrderLines.Columns["deleteBtn"].Index) return;
Int32 orderLineID = (Int32)gvOrderLines[1, e.RowIndex].Value;
DialogResult result = MessageBox.Show("Do you want to delete this item? ","Delete Item",MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
using (SqlConnection conn = new SqlConnection(connection))
{
SqlCommand comm;
comm = new SqlCommand("del_OrderLine", conn);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter("#orderLineID", SqlDbType.Int));
comm.Parameters["#orderLineID"].Value = orderLineID;
comm.Parameters.Add("#ReturnValue", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
try
{
conn.Open();
comm.ExecuteNonQuery();
intOrderID = (int)comm.Parameters["#ReturnValue"].Value;
}
catch
{
//tba
}
finally
{
comm.Dispose();
conn.Close();
}
}
}
populateOrderLines(intOrderID); // This repopulates the gv so why is it blank?
populateOrderTotals(intOrderID);
}
Any suggestions?
All the best,
Numb
Put these lines within the if (result == DialogResult.Yes) block:
populateOrderLines(intOrderID); // This repopulates the gv so why is it blank?
populateOrderTotals(intOrderID);
Related
Im new to C#, so bear with me. Im using C#, a Form, and SQL Server 2012.
I have written some code that uses a Background Worker (from the form designer) and a progress bar to illustrate to the user the percentage of data that needs to be loaded from a SQL query until all records are completely read.
The problem Im having is that when the Worker is completed, I get many duplicate records listed in the datagridview. I should be getting only 14 returned records from my query, but I get many more (which are duplicates).
Im not sure why? Im sure there is a bug here (and that my beginnner code can be improved).
Can someone help my understand why Im getting duplicate records once the worker completes? My code is below
private void button2_Click(object sender, EventArgs e)
{
bgw.WorkerReportsProgress = true;
bgw.WorkerSupportsCancellation = false;
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
System.Threading.Thread.Sleep(10);
bgw.RunWorkerAsync();
}
DataSet ds = new DataSet();
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
string query = "Select * from Stars_Pillars";
string connetionString = null;
SqlConnection cnn;
connetionString = "Server=xxx\\xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx;";
cnn = new SqlConnection(connetionString);
SqlDataAdapter da = new SqlDataAdapter(query, cnn);
//DataSet ds = new DataSet();
try
{
cnn.Open();
int resda, startrow, pagesize, pageno;
pagesize = getRowCount();
progressBar1.Maximum = pagesize;
pageno = 1;
ds.Tables.Clear();
dataGridView1.Rows.Clear();
while (true)
{
if (!bgw.CancellationPending)
{
startrow = pageno;
resda = da.Fill(ds, startrow, pagesize, "Stars_Pillars");
if (resda == 0)
{
e.Cancel = true;
break;
}
else
{
System.Threading.Thread.Sleep(10);
int percents = (pageno * 100 / pagesize);
bgw.ReportProgress(percents, pageno);
pageno++;
}
}
else
{
e.Cancel = true;
break;
}
}
da.Dispose();
cnn.Close();
cnn.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.PerformStep();
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Value = progressBar1.Maximum;
progressBar1.Visible = false;
dataGridView1.DataSource = ds.Tables[0];
}
private int getRowCount()
{
int count = 0;
string connetionString;
connetionString = "Server=xxxx\\xxxx;Initial Catalog=xxxx;User ID=xxxx;Password=xxxx;";
SqlConnection conn = new SqlConnection(connetionString);
string sql = "SELECT COUNT(Serial_Number) FROM [Stars_Pillars]";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
count = (int)dr[0];
}
}
catch { }
finally
{
conn.Close();
}
return count;
}
there is a lot of improvements to make in your code...you should never use while (true) it is extremely bad practice and you can end with infinite loop. also, there is no way to measure and show progress of filling a dataset with dataAdapter.
if the operation takes time show a Marquee style progress bar.
for start try this code to load data from database to the DataSet object:
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
try
{
string query = "Select * from Stars_Pillars";
connetionString = "Server=xxx\\xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx;";
using(cnn = new SqlConnection(connetionString))
{
cnn.Open();
using(SqlDataAdapter da = new SqlDataAdapter(query, cnn))
{
adapter.Fill(ds);
cnn.Close();
}
}
} catch (Exception ex) {
// handle errors here and close connetion if its open
}
}
You must be getting an exception with your code.
You cannot access UI element from bgwDoWork()
The below line must be failing.
dataGridView1.Rows.Clear();
Please check.
I am trying to develop a restaurant billing application in windows form.
so I created dynamic buttons.
now I need a table which will retrieve data from database for each button click.
How can it possible?
private void newb_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
// textBox1.Text = btn.Text;
connection con = new connection();
con.connecting();
// Button b = new Button();
int i = 0;
var query = "select itemname,itemcode,price from item_master where itemcode =" + btn.Name;
MySqlCommand cmd = new MySqlCommand(query, con.con);
while (i < 10)
{
MySqlDataAdapter sda = new MySqlDataAdapter();
DataTable dt = new DataTable();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bsource = new BindingSource();
bsource.DataSource = dbdataset;
dataGridView1.DataSource = bsource;
// MessageBox.Show(btn.Name);
i++;
}
// sda.Update(dbdataset);
// =dataGridView1.Rows[0]
//// MySqlDataReader mdr;
//// mdr = cmd.ExecuteReader();
// while (mdr.Read())
// {
//// textBox1.Text = (mdr["itemname"].ToString());
// }
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
I have an issue where I am trying to sort a Datagridview by the Combobox DisplayMember instead of the ValueMember.
The Datagridview is Databound to a Datatable which is populated from a SQL query and the Combobox is populated by the results of a LinqQuery.
Code-behind for Form populating Datagridview and Sorting
Dictionary<string, string> search = new Dictionary<string, string>();
search.Add("ID", "ID");
search.Add("ClientID", "ClientID");
search.Add("ClientCode", "ClientCode");
search.Add("BatchRef", "BatchRef");
search.Add("CaseRef", "CaseRef");
search.Add("AccountNo", "AccountNo");
search.Add("MeterName", "MeterName");
search.Add("MeterAddress", "MeterAdd");
search.Add("MeterPostcode", "MeterPostcode");
search.Add("AgentID", "AgentID");
search.Add("CompletedDate", "CompletedDate");
search.Add("SubmittedDate", "SubmittedDate");
Systems.PopulateDataGrid(search, dgvSearch, SQLHelper.FillDataTable(sql, CommandType.Text, searchParameters));
private void dgvSearch_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
ListSortDirection direction;
if (dgvSearch.Columns[e.ColumnIndex].HeaderText == "Agent")
{
if (dgvSearch.SortOrder == System.Windows.Forms.SortOrder.Ascending)
direction = ListSortDirection.Descending;
else
direction = ListSortDirection.Ascending;
dgvSearch.Sort(dgvSearch.Columns[e.ColumnIndex], direction);
}
}
Systems.PopulateDatagrid
internal static void PopulateDataGrid(Dictionary<string, string> dataGrid, DataGridView dgv, DataTable dt)
{
dgv.AutoGenerateColumns = false;
foreach (KeyValuePair<string, string> row in dataGrid)
{
dgv.Columns[row.Key].DataPropertyName = row.Value;
}
dgv.DataSource = dt;
}
SQLHelper.FillDatatable
internal static DataTable FillDataTable(string strSQL, CommandType CT, List<SqlParameter> parameters)
{
var ds = new DataSet("UMDS");
DataTable dt = ds.Tables.Add("UMDT");
ds.EnforceConstraints = false;
using (var cn = new SqlConnection(SQLHelper.ConnectionString))
{
using (var cmd = new SqlCommand(strSQL, cn))
{
cmd.CommandType = CT;
if (parameters != null)
{
DateTime dateTime;
foreach (SqlParameter p in parameters)
{
if (p.Value == null || string.IsNullOrEmpty(p.Value.ToString()) || p.Value.ToString() == Systems.MASKEDDATE || p.Value.ToString() == Systems.MASKEDTIME)
{
p.Value = DBNull.Value;
}
else if (DateTime.TryParse(p.Value.ToString(), out dateTime))
{
p.Value = dateTime;
}
cmd.Parameters.Add(p);
}
}
try
{
cn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
dt.Load(dr);
}
}
catch (SqlException ex)
{
Systems.Msg("Database Error", "Error Loading Data from Database. Please try again.\n\n" + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
return dt;
}
When clicking on the Header for "AgentID" it is sorting by the ValueMember instead of the DisplayMember.
Answering my own question:
Managed to find the answer on another SO question after some more googling.
Sorting DataGridView by Column.DisplayMember
I have 2 cascading combo-box in windows form application. I have textbox for price and unit. when I select first combobox, second combobox gets populated. I want textbox for price and unit to be filled only on second combobox selection.
My problem is when the form is loaded both textboxes are filled with values from table and not on combobox selection changed.
my code is:
private void Purchase_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'supplierDataSet.Supplier' table. You can move, or remove it, as needed.
this.supplierTableAdapter.Fill(this.supplierDataSet.Supplier);
fillName();
comboBoxName.SelectedIndex = -1;
}
private void fillName()
{
string str = "Select distinct Item_Name from Item";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Name";
}
}
}
}
private void fillMake()
{
string str = "Select Item_Make from Item Where Item_Name=#Item_Name";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
cmd.Parameters.AddWithValue("#Item_Name", comboBoxName.Text);
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxMake.DataSource = dtItem;
comboBoxMake.ValueMember = "Item_Make";
comboBoxMake.DisplayMember = "Item_Make";
}
}
}
}
private void comboBoxName_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxName.Text))
{
comboBoxMake.Enabled = true;
fillMake();
comboBoxMake.SelectedIndex = -1;
}
}
private void comboBoxMake_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxMake.Text))
{
textBoxPrice.Enabled = true;
textBoxUoM.Enabled = true;
}
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * from Item Where Item_Make='" + comboBoxMake.Text + "' AND Item_Name='" + comboBoxName.Text + "'", con);
SqlDataReader reader;
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
reader = cmd.ExecuteReader();
while (reader.Read())
{
textBoxPrice.Text = Convert.ToString(reader["Price"]);
textBoxUoM.Text = Convert.ToString(reader["Unit"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
I am stuck here. please help.
Try changing SelectedIndex = -1 to SelectedItem = -1 in Purchase_Load and ComboBox1_SelectedIndexChanged.
my error is simple but for me it is hard to fix it because my knowledge is not good . which is when i Enter the record by clicking the Addbutton of AddStudent record then the record that i deleted like record StudentID = 1, FirstName =Raju ,LastName=Abbasi
After Delete it again and press save Change even After that when i again try to use the ID=1 means enter the Record with ID=1 that i have been deleted and record the StudentID=1 ,FirstName =Ram ,LastName=Rakish .Then error is occur which is
private static SqlDataAdapter CreateSutdentDataAdapter()
{
string gettSQL = "SELECT * FROM Student";
string insertSQL = "SET IDENTITY_INSERT Student ON;INSERT INTO Student(StudentID, FirstName,LastName,Gender,GPA,MyImage)" +
"VALUES (#StudentID,#FirstName,#LastName,#Gender,#GPA,#MyImage);SET IDENTITY_INSERT Student OFF";
string updateSQL = "UPDATE Student SET FirstName=#FirstName,LastName=#LastName ,Gender=#Gender, MyImage=#MyImage," +
" GPA=#GPA WHERE StudentID=#StudentID";
string deleteSQL = "DELETE FROM Student WHERE StudentID=#StudentID";
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand(gettSQL, ConnectionManager.GetConnection());
dataAdapter.InsertCommand = new SqlCommand(insertSQL, ConnectionManager.GetConnection());
dataAdapter.InsertCommand.Parameters.Add("#StudentID", SqlDbType.Int).SourceColumn = "StudentID";
dataAdapter.InsertCommand.Parameters.Add("#FirstName", SqlDbType.VarChar,25 ).SourceColumn = "FirstName";
dataAdapter.InsertCommand.Parameters.Add("#LastName", SqlDbType.VarChar, 25 ).SourceColumn = "LastName";
dataAdapter.InsertCommand.Parameters.Add("#Gender", SqlDbType.VarChar ,1).SourceColumn = "Gender";
dataAdapter.InsertCommand.Parameters.Add("#GPA", SqlDbType.Float ).SourceColumn = "GPA";
dataAdapter.InsertCommand.Parameters.Add("#MyImage", SqlDbType.VarBinary).SourceColumn = "MyImage";
dataAdapter.UpdateCommand = new SqlCommand(updateSQL, ConnectionManager.GetConnection());
dataAdapter.UpdateCommand.Parameters.Add("#StudentID", SqlDbType.Int).SourceColumn = "StudentID";
dataAdapter.UpdateCommand.Parameters.Add("#FirstName", SqlDbType.VarChar,25 ).SourceColumn = "FirstName";
dataAdapter.UpdateCommand.Parameters.Add("#LastName", SqlDbType.VarChar, 25 ).SourceColumn = "LastName";
dataAdapter.UpdateCommand.Parameters.Add("#Gender", SqlDbType.VarChar ,1).SourceColumn = "Gender";
dataAdapter.UpdateCommand.Parameters.Add("#GPA", SqlDbType.Float ).SourceColumn = "GPA";
dataAdapter.UpdateCommand.Parameters.Add("#MyImage", SqlDbType.VarBinary).SourceColumn = "MyImage";
dataAdapter.DeleteCommand = new SqlCommand(deleteSQL, ConnectionManager.GetConnection());
dataAdapter.DeleteCommand.Parameters.Add("#StudentID", SqlDbType.Int).SourceColumn = "StudentID";
return dataAdapter;
}
private static void DefinestudentTableSchema(DataTable table)
{
DataColumn StudentIDColumn = table.Columns.Add("StudentID", typeof(string));
StudentIDColumn.AllowDBNull = false;
table.PrimaryKey = new DataColumn[] { StudentIDColumn };
DataColumn StudentFirstName = table.Columns.Add("FirstName", typeof(string));
StudentFirstName.MaxLength = 150;
DataColumn StudentLastName = table.Columns.Add("LastName", typeof(string));
StudentLastName.MaxLength = 150;
DataColumn StudentGender = table.Columns.Add("Gender", typeof(string ));
DataColumn StudentGPA = table.Columns.Add("GPA", typeof(string ));
DataColumn StudentImage = table.Columns.Add("MyImage", typeof(Byte[]));
}
private static DataSet CreateStudentTrackerDataSet()
{
DataSet StudentTrackerDataSet = new DataSet();
DataTable StudentTable = StudentTrackerDataSet.Tables.Add("Student");
DefinestudentTableSchema(StudentTable);
return StudentTrackerDataSet;
}
public static DataSet GetData()
{
DataSet StudentTrakerDataSet = CreateStudentTrackerDataSet();
StudentTrakerDataSet.EnforceConstraints = false;
StudentDataAdapter.Fill(StudentTrakerDataSet.Tables["Student"]);
StudentTrakerDataSet.EnforceConstraints = true;
return StudentTrakerDataSet;
}
public AddModifyStudentRecords(DataSet ds, DataRow row)
{
public static void SaveData(ref DataSet changesDataSet)
{
DataSet addedDataSet = changesDataSet.GetChanges(DataRowState.Added);
if (addedDataSet != null)
{
StudentDataAdapter.Update(addedDataSet.Tables["Student"]);
changesDataSet.Merge(addedDataSet); // Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints
}
DataSet modifiedDataSet = changesDataSet.GetChanges(DataRowState.Modified);
if (modifiedDataSet != null)
{
StudentDataAdapter.Update(modifiedDataSet.Tables["Student"]);
changesDataSet.Merge(modifiedDataSet);
}
DataSet deletedDataSet = changesDataSet.GetChanges(DataRowState.Deleted);
if (deletedDataSet != null)
{
StudentDataAdapter.Update(deletedDataSet.Tables["Student"]);
deletedDataSet.Merge(deletedDataSet);
}
here is my Addmodifyform logic for add the StudentID
public partial class AddModifyStudentRecords : Form
{
DataSet StudentTrackerDataSet;
DataRow currentRow;
public AddModifyStudentRecords()
{
InitializeComponent();
}
public AddModifyStudentRecords(DataSet ds)
{
InitializeComponent();
StudentTrackerDataSet = ds;
currentRow = null;
}
public AddModifyStudentRecords(DataSet ds, DataRow row)
{
InitializeComponent();
StudentTrackerDataSet = ds;
currentRow = row;
textBox1.Text =currentRow["StudentID"] .ToString();
textBox2.Text = currentRow["FirstName"].ToString();
textBox4.Text = currentRow["LastName"].ToString();
textBox3.Text = currentRow["Gender"].ToString();
textBox5.Text = currentRow["GPA"].ToString();
txtBrowseFile.Text = currentRow["MyImage"].ToString ();
byte[] data = (byte[])currentRow ["MyImage"];
MemoryStream ms = new MemoryStream(data);
pictureBox1.Image = Image.FromStream(ms);
string StudentID = textBox1.Text.ToString();
string StudentFirstName = textBox2.Text.ToString();
string StudentLastName = textBox4.Text.ToString();
string Gender = textBox3.Text.ToString();
string GPA = textBox5.Text.ToString();
Image MyImage = pictureBox1.Image;
DataTable table = StudentTrackerDataSet.Tables["Student"];
if (currentRow == null) {
currentRow = table.NewRow();
currentRow["StudentID"] = textBox1.Text.ToString();
table.Rows.Add(currentRow );
}
currentRow .BeginEdit();
currentRow ["StudentID" ]=StudentID ;
currentRow["FirstName"] = StudentFirstName;
currentRow["LastName"] = StudentLastName;
currentRow["Gender"] = Gender;
currentRow["GPA"] = GPA;
currentRow["MyImage"] = convertToByte(txtBrowseFile.Text);
currentRow.EndEdit();
Close();
}
public partial class AditStudent : Form
{
// Creat the Class variabl Dataset to track the Student
private DataSet StudentTrackerDataset;
public AditStudent()
{
InitializeComponent();
dataGridView1.DataError += DataGridView1_DataError;
StudentTrackerDataset = ProjectOfSchool.DataAccessLayer.DAC.GetData();
DataTable StudentTable = StudentTrackerDataset.Tables["Student"];
dataGridView1.DataSource = StudentTable;
//StudentTable.Columns["ID"].AutoIncrement = true;
for (int i = 0; i < dataGridView1.Columns.Count; i++)
if (dataGridView1.Columns[i] is DataGridViewImageColumn)
{
((DataGridViewImageColumn)dataGridView1.Columns[i]).ImageLayout = DataGridViewImageCellLayout.Stretch;
break;
}
}
private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
string message = string.Format("Error in {0} columan in row {1}:{2}", e.ColumnIndex, e.RowIndex, e.Exception.Message);
MessageBox.Show(message, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
private void button1_Click(object sender, EventArgs e)
{
AddModifyStudentRecords AddStudent = new AddModifyStudentRecords(StudentTrackerDataset);
AddStudent.ShowDialog();
}
private void button2_Click(object sender, EventArgs e)
{
object id = dataGridView1.CurrentRow.Cells["StudentID"].Value;
DataRow StudentRow = StudentTrackerDataset.Tables["Student"].Rows.Find(id);
AddModifyStudentRecords modifyStudent = new AddModifyStudentRecords(StudentTrackerDataset, StudentRow);
modifyStudent.ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure", "Delete Current Row", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
object id = dataGridView1.CurrentRow.Cells["StudentID"].Value;
DataRow currentRow = StudentTrackerDataset.Tables["Student"].Rows.Find(id);
currentRow.Delete();
}
}
private void button4_Click(object sender, EventArgs e)
{
if (!StudentTrackerDataset.HasChanges())
{
MessageBox.Show("There are no Change to Save ", "Save Changes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
try
{
DataSet changesDateSet = StudentTrackerDataset.GetChanges();
ProjectOfSchool.DataAccessLayer.DAC.SaveData(ref changesDateSet);
StudentTrackerDataset.Merge(DAC.GetData());
MessageBox.Show("Data Save Successfully.", "Save Changes");
}
catch (SqlException ex)
{
MessageBox.Show("Data Not Saved:" + ex.Message, "Save Changes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
private void button5_Click(object sender, EventArgs e)
{
if (!StudentTrackerDataset.HasChanges())
{
MessageBox.Show("There are no Changes to Save.", "Save Changes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
DialogResult result = MessageBox .Show ("Are you Sure?","Reject Changes", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes )
{
StudentTrackerDataset.RejectChanges();
}
}
}
And When i terminate the program and re execute the program then i saw that StudntID=1 is also save to Database with ID=1
or When i Delete the StudentID =1 and press save Change after press save Change when i also Terminate the program and re exicute the program and after that when i Enter the StudentID =1 Then no error is occur
And other way without termination is to Delete the record StudentID1 but when you Add the Student record but not Add the StudentID=1 But add the StudentID other then 1 in this case error is also not happend . Dear Sherik I have been solve my other error but i have still error which is in my Tittle So please responding me for this error And i re edited my code also So please replay me Thanks
I have record in my Database which have following Datatype as
StudentID=INT,
FirstName=VarChar,
LastName=VarChar,
Gender=Varchar,
GPA=Float,
MyImage=Vabinary (MAX)
Or may be Datarow fail to Delete the record or Update the record. I don't know please tell me and thanks to reply me and I am waiting for your reply.
The error message seems to indicate that you are hitting a Primary Key constraint.
I would suggest that you first stop allowing the user to enter the Student ID field. Let it be generated as an auto increment key in whatever database you are using. In Access, it is called AutoNumber.
Once you have done that, re test and post the results.