Related
public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string q2 = "insert into database.gym (name,weight,height,add_class,gender,fees) values('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.textBox3.Text + "','" + this.comboBox1.Text + "','" + this.comboBox2.Text + "','" + this.comboBox3.Text + " ') ;";
SqlConnection con = new SqlConnection(ss);
SqlCommand cmd = new SqlCommand(q2, con);
SqlDataReader read;
try
{
con.Open();
read = cmd.ExecuteReader();
MessageBox.Show("Welcome to our gym");
while (read.Read()) { };
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
insert into database.gym
Instead of this use a valid table name
insert into Table
The Correct Syntax is [Database].[Schema].[TableName]
using System.Data.SqlClient;
namespace EHR
{
public partial class imagery : Form
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\wittyse\Desktop\database_EHR\EHR.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd;
DataTable dt2 = new DataTable();
public imagery()
{
InitializeComponent();
}
public void readdatagrid1()
{
//con.Open();
SqlDataAdapter dpeo = new SqlDataAdapter("Select Img_ID,PEOPLE_INFO.people_ID,PEOPLE_INFO.Name,Imgs,Result from PEOPLE_INFO,IMAGERY_DIAGNOSTIC,MG_NAM where IMAGERY_DIAGNOSTIC.Img_ID=MG_NAM.Mg_nm_ID and PEOPLE_INFO.people_ID=IMAGERY_DIAGNOSTIC.People_ID", con);
DataSet dpep = new DataSet();
dpeo.Fill(dpep, "IMAGERY_DIAGNOSTIC");
dataGridView1.DataSource = dpep.Tables["IMAGERY_DIAGNOSTIC"];
con.Close();
}
private void imagery_Load(object sender, EventArgs e)
{
//dataGridView1.DataSource = null;
readdatagrid1();
SqlDataAdapter dz = new SqlDataAdapter("Select * from MG_NAM order by Mg_nm_ID", con);
DataSet dzo = new DataSet();
dz.Fill(dzo, "MG_NAM");
comboBox1.DataSource = dzo.Tables["MG_NAM"];
comboBox1.DisplayMember = "Imgs";
SqlDataAdapter da = new SqlDataAdapter("Select Name from PEOPLE_INFO order by people_ID", con);
DataSet ds = new DataSet();
da.Fill(ds, "PEOPLE_INFO");
comboBox2.DataSource = ds.Tables["PEOPLE_INFO"];
comboBox2.DisplayMember = "Name";
con.Close();
}
public int comck=0;
public int idx;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
con.Close();
string Query = "Select Mg_nm_ID,Imgs from MG_NAM where Imgs='" + comboBox1.Text + "'";
con.Open();
SqlCommand createCommand = new SqlCommand(Query, con);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
textBox4.Text = dr.GetInt32(0).ToString();
//textBox1.Text = dr.GetInt32(1).ToString();
idx = Convert.ToInt32(textBox4.Text);
}
dr.Close();
comck = 1;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(id+" index is "+comboBox1.SelectedIndex,"info");
}
public int comck2 = 0;
public int id;
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
con.Close();
string Query = "Select people_ID,Name from PEOPLE_INFO where Name='" + comboBox2.Text + "'";
con.Open();
SqlCommand createCommand = new SqlCommand(Query, con);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
textBox2.Text = dr.GetInt32(0).ToString();
//textBox1.Text = dr.GetInt32(1).ToString();
id = Convert.ToInt32(textBox2.Text);
}
dr.Close();
comck2 = 1;
}
private void button2_Click(object sender, EventArgs e)
{
if (comck == 0 & comck2 == 0 || textBox3.Text == "")
{
MessageBox.Show("you must select or inter data","info");
}
else
{
con.Close();
cmd = new SqlCommand("Insert into IMAGERY_DIAGNOSTIC(People_ID,Mg_Nam,Result) values ('" + id + "','" + idx + "','" + textBox3.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Added new IMAGERY DIAGNOSTIC ", "ADD", MessageBoxButtons.OK, MessageBoxIcon.Information);
dataGridView1.DataSource = null;
con.Close();
readdatagrid1();
}
// MessageBox.Show("info save"+comboBox1.SelectedIndex," info ");
}
private void button3_Click(object sender, EventArgs e)
{
if (selectgrid == 0)
{ MessageBox.Show("you must select record to delet it","Info",MessageBoxButtons.OK,MessageBoxIcon.Information); }
else
{
cmd = new SqlCommand("Delete From IMAGERY_DIAGNOSTIC Where Img_ID='" + bindex + "'", con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("You delete recored successfully", "delete", MessageBoxButtons.OK, MessageBoxIcon.Information);
dataGridView1.DataSource = null;
con.Close();
readdatagrid1();
}
}
public int bindex;
public int selectgrid = 0;
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
textBox1.Text = row.Cells["People_ID"].Value.ToString(); //roll type to update
comboBox2.Text = row.Cells["Name"].Value.ToString();
textBox3.Text = row.Cells["Result"].Value.ToString();
string dex = row.Cells["Img_ID"].Value.ToString();
bindex = Convert.ToInt32(dex); //Bld_ID in integer format | for Query
selectgrid = 1;
}
}
}
}
replace the following code dataGridView1.DataSource = dpep.Tables["IMAGERY_DIAGNOSTIC"];
with
dataGridView1.DataSource = new BindingSource { DataSource =dpep.Tables["IMAGERY_DIAGNOSTIC"] };
I'm trying to create a master-detail form with datagridviews all in code. The SELECT/fill part is working fine, but I am having trouble with UPDATE/INSERT/DELETE (which should happen automatically when the form is closed). The following code gives the error:
Update requires the UpdateCommand to have a connection object. The
Connection property of the UpdateCommand has not been initialized.
on the .Update line.
I tried moving the connection out of the GetData() procedure, but that was not the answer.
What should I be doing?
Code:
Imports System.Data
Imports System.Data.OleDb
Public Class TestMe2
Private lblSelector As New Label
Private cbSelector As New ComboBox
Private bsSelector As New BindingSource
Private daMaster As New OleDbDataAdapter
Private dgMaster As New DataGrid
Private bsMaster As New BindingSource
Private dgLookup As New DataGrid
Private bsLookups As New BindingSource
Private dsGFF As New DataSet
Private cnn As New OleDbConnection
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.Controls.Add(lblSelector)
lblSelector.Location = New System.Drawing.Point(0, 0)
lblSelector.Text = "FileType"
Me.Controls.Add(cbSelector)
cbSelector.Location = New System.Drawing.Point(Me.lblSelector.Width, 0)
Me.Controls.Add(dgMaster)
dgMaster.Location = New System.Drawing.Point(0, cbSelector.Height)
dgMaster.Height = 300
dgMaster.Width = 2000
Me.Controls.Add(dgLookup)
dgLookup.Location = New System.Drawing.Point(0, cbSelector.Height + dgMaster.Height)
dgLookup.Height = 100
dgLookup.Width = 1000
End Sub
Private Sub TestMe2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
bsSelector.DataSource = dsGFF
cbSelector.DataSource = bsSelector
bsMaster.DataSource = dsGFF
dgMaster.DataSource = bsMaster
bsLookups.DataSource = dsGFF
dgLookup.DataSource = bsLookups
GetData()
bsMaster.DataSource = bsSelector
bsMaster.DataMember = "FileTypesToGFFTranslator"
bsLookups.DataSource = bsMaster
bsLookups.DataMember = "GFFTranslatorToTranslations"
'dgMaster.autoresizecolumns()
End Sub
Private Sub GetData()
Dim command As New OleDbCommand
Dim parameter As New OleDbParameter
' where's the data?
Dim cnnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\GFFTranslator.accdb"
cnn = New OleDb.OleDbConnection(cnnString)
' set up up the selector
Dim daSelector As New OleDbDataAdapter("SELECT FileType FROM vwFileTypeSelection", cnn)
daSelector.Fill(dsGFF, "vwFileTypeSelection")
bsSelector.DataSource = dsGFF
bsSelector.DataMember = "vwFileTypeSelection"
cbSelector.ValueMember = "FileType"
cbSelector.DisplayMember = "FileType"
daSelector.Fill(dsGFF)
' set up the master
daMaster = New OleDbDataAdapter("SELECT * FROM GFFTranslator", cnn)
daMaster.Fill(dsGFF, "GFFTranslator")
daMaster.UpdateCommand = New OleDbCommand("UPDATE GFFTRanslator" & _
" SET FileType = ?" & _
" , FieldPosition = ?" & _
" , FieldType = ?" & _
" , StartRepeatingSection = ?" & _
" , FileTypeIdentifier = ?" & _
" , Flag = ?" & _
" , DataStart = ?" & _
" , DataLength = ?" & _
" , NextLine = ?" & _
" , Lookup = ?" & _
" , Title = ?" & _
" , ExtraInfo = ?" & _
" WHERE FileType = ?" & _
" AND FieldPosition = ? ;")
daMaster.UpdateCommand.Parameters.Add("#FileType", OleDbType.VarChar, 255, "FileType")
daMaster.UpdateCommand.Parameters.Add("#FieldPosition", OleDbType.Integer, 4, "FieldPosition")
daMaster.UpdateCommand.Parameters.Add("#FieldType", OleDbType.VarChar, 255, "FieldType")
daMaster.UpdateCommand.Parameters.Add("#StartRepeatingSection", OleDbType.Boolean, 1, "StartRepeatingSection")
daMaster.UpdateCommand.Parameters.Add("#FileTypeIdentifier", OleDbType.Boolean, 1, "FileTypeIdentifier")
daMaster.UpdateCommand.Parameters.Add("#Flag", OleDbType.Boolean, 1, "Flag")
daMaster.UpdateCommand.Parameters.Add("#DataStart", OleDbType.Integer, 5, "DataStart")
daMaster.UpdateCommand.Parameters.Add("#DataLength", OleDbType.Integer, 5, "DataLength")
daMaster.UpdateCommand.Parameters.Add("#NextLine", OleDbType.Boolean, 1, "NextLine")
daMaster.UpdateCommand.Parameters.Add("#Lookup", OleDbType.Boolean, 1, "Lookup")
daMaster.UpdateCommand.Parameters.Add("#Title", OleDbType.VarChar, 255, "Title")
daMaster.UpdateCommand.Parameters.Add("#ExtraInfo", OleDbType.VarChar, 255, "ExtraInfo")
' set up the lookup
Dim daLookup As New OleDbDataAdapter("SELECT * FROM Translations", cnn)
daLookup.Fill(dsGFF, "Translations")
' link everything together
Try
Dim drMaster As New DataRelation("FileTypesToGFFTranslator" _
, dsGFF.Tables("vwFileTypeSelection").Columns("FileType") _
, dsGFF.Tables("GFFTranslator").Columns("FileType"))
dsGFF.Relations.Add(drMaster)
Dim dcMaster As DataColumn() = New DataColumn() {dsGFF.Tables("GFFTranslator").Columns("FileType"), dsGFF.Tables("GFFTranslator").Columns("FieldType")}
Dim dcLookup As DataColumn() = New DataColumn() {dsGFF.Tables("Translations").Columns("FileType"), dsGFF.Tables("Translations").Columns("FieldType")}
Dim drLookup As New DataRelation("GFFTranslatorToTranslations" _
, dcMaster _
, dcLookup)
dsGFF.Relations.Add(drLookup)
Catch ex As Exception
MessageBox.Show("Error: " & ex.Message)
End Try
End Sub
Protected Overrides Sub Finalize()
Me.Validate()
Me.daMaster.Update(dsGFF.Tables("GFFTranslator"))
Me.dsGFF.AcceptChanges()
MyBase.Finalize()
End Sub
End Class
In the code below, you are passing a connection object to your SELECT command.
' set up the master
daMaster = New OleDbDataAdapter("SELECT * FROM GFFTranslator", cnn)
Once the .Fill() method is done, your connection object is closed.
daMaster.Fill(dsGFF, "GFFTranslator")
You are now trying to create an UPDATE command but you aren't passing it a connection object for it to work with.
daMaster.UpdateCommand = New OleDbCommand("UPDATE GFFTRanslator" & _
" SET FileType = ?" & _
" , FieldPosition = ?" & _
" , FieldType = ?" & _
" , StartRepeatingSection = ?" & _
" , FileTypeIdentifier = ?" & _
" , Flag = ?" & _
" , DataStart = ?" & _
" , DataLength = ?" & _
" , NextLine = ?" & _
" , Lookup = ?" & _
" , Title = ?" & _
" , ExtraInfo = ?" & _
" WHERE FileType = ?" & _
" AND FieldPosition = ? ;")
daMaster.UpdateCommand.Parameters.Add("#FileType", OleDbType.VarChar, 255, "FileType")
daMaster.UpdateCommand.Parameters.Add("#FieldPosition", OleDbType.Integer, 4, "FieldPosition")
daMaster.UpdateCommand.Parameters.Add("#FieldType", OleDbType.VarChar, 255, "FieldType")
daMaster.UpdateCommand.Parameters.Add("#StartRepeatingSection", OleDbType.Boolean, 1, "StartRepeatingSection")
daMaster.UpdateCommand.Parameters.Add("#FileTypeIdentifier", OleDbType.Boolean, 1, "FileTypeIdentifier")
daMaster.UpdateCommand.Parameters.Add("#Flag", OleDbType.Boolean, 1, "Flag")
daMaster.UpdateCommand.Parameters.Add("#DataStart", OleDbType.Integer, 5, "DataStart")
daMaster.UpdateCommand.Parameters.Add("#DataLength", OleDbType.Integer, 5, "DataLength")
daMaster.UpdateCommand.Parameters.Add("#NextLine", OleDbType.Boolean, 1, "NextLine")
daMaster.UpdateCommand.Parameters.Add("#Lookup", OleDbType.Boolean, 1, "Lookup")
daMaster.UpdateCommand.Parameters.Add("#Title", OleDbType.VarChar, 255, "Title")
daMaster.UpdateCommand.Parameters.Add("#ExtraInfo", OleDbType.VarChar, 255, "ExtraInfo")
So, to fix this, do the following:
" AND FieldPosition = ? ;", cnn) // Pass your connection object here.
I want to create a Crystal Report at runtime by selecting the fields for the report from the treeview. The treeview consists of table names and the column names as the child node. After selecting the column names from the treeview, a "Generate Report" button has to be clicked, which will display the Crystal Report of the selected fields. How can I do this?
Public Class Form1
Dim objRpt As CrystalReport1
Dim con As New SqlConnection
Private Function CreateSelectQueryAndParameters() As String
Dim reportDocument As New ReportDocument
Dim paramFields As New ParameterFields
Dim paramField As ParameterField
Dim paramDiscreteValue As ParameterDiscreteValue
Dim query As String = "SELECT "
Dim columnNo As Integer = 0
If CheckBox1.Checked Then
columnNo = columnNo + 1
query = query.Insert(query.Length, "pcode as Column" + columnNo.ToString())
paramField = New ParameterField()
paramField.Name = "col" + columnNo.ToString()
paramDiscreteValue = New ParameterDiscreteValue()
paramDiscreteValue.Value = "Property Code"
paramField.CurrentValues.Add(paramDiscreteValue)
paramFields.Add(paramField)
End If
If CheckBox2.Checked Then
columnNo = columnNo + 1
If (query.Contains("Column")) Then
query = query.Insert(query.Length, ", ")
End If
query = query.Insert(query.Length, "pname as Column" +
columnNo.ToString())
paramField = New ParameterField()
paramField.Name = "col" + columnNo.ToString()
paramDiscreteValue = New ParameterDiscreteValue()
paramDiscreteValue.Value = "Property Name"
paramField.CurrentValues.Add(paramDiscreteValue)
paramFields.Add(paramField)
End If
For i As Integer = columnNo To 2
columnNo = columnNo + 1
paramField = New ParameterField()
paramField.Name = "col" + columnNo.ToString()
paramDiscreteValue = New ParameterDiscreteValue()
paramDiscreteValue.Value = ""
paramField.CurrentValues.Add(paramDiscreteValue)
paramFields.Add(paramField)
Next
CrystalReportViewer1.ParameterFieldInfo = paramFields
query += " FROM propdb"
Return query
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
objRpt = New CrystalReport1()
con.ConnectionString = "Data Source=MY-PC; Initial Catalog=hrmdb; Integrated Security=True"
con.Open()
Dim query As String = CreateSelectQueryAndParameters()
If Not query.Contains("Column") Then
MessageBox.Show("No selection to display!")
Return
End If
Try
**' I DON'T KNOW WHAT CODE TO ADD HERE'**
CrystalReportViewer1.ReportSource = objRpt
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
con.Close()
End Sub
End Class
I had a similar program in C#, but they used Access in it and I am using SQL Server now:
public partial class Form1 : Form
{
CrystalReport1 objRpt;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
objRpt = new CrystalReport1();
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\db1.mdb";
//Get Select query Strring and add parameters to the
//Crystal report.
string query = CreateSelectQueryAndParameters();
//if there is no item select,then exit from the method.
if (!query.Contains("Column"))
{
MessageBox.Show("No selection to display!");
return;
}
try
{
OleDbConnection Conn = new OleDbConnection(connString);
OleDbDataAdapter adepter = new OleDbDataAdapter(query, connString);
DataSet1 Ds = new DataSet1();
adepter.Fill(Ds, "Customer");
objRpt.SetDataSource(Ds);
crystalReportViewer1.ReportSource = objRpt;
}
catch (OleDbException oleEx)
{
MessageBox.Show(oleEx.Message);
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
/// <summary>
/// This method is used to
/// 1. create SELECT query according to the selected column names and
/// 2. create parameters and assign values for that parameter that correspond to
/// the crystal report.
/// NOTE: This parameter is used to display column names of the Crystal Report
/// according to the user selection.
/// </summary>
/// <returns></returns>
private string CreateSelectQueryAndParameters()
{
ReportDocument reportDocument;
ParameterFields paramFields;
ParameterField paramField;
ParameterDiscreteValue paramDiscreteValue;
reportDocument = new ReportDocument();
paramFields = new ParameterFields();
string query = "SELECT ";
int columnNo = 0;
if (chbCode.Checked)
{
columnNo++;
query = query.Insert(query.Length, "Code as Column" + columnNo.ToString());
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "Customer Code";
paramField.CurrentValues.Add(paramDiscreteValue);
//Add the paramField to paramFields
paramFields.Add(paramField);
}
if (chbFirstName.Checked)
{
columnNo++;
if (query.Contains("Column"))
{
query = query.Insert(query.Length, ", ");
}
query = query.Insert(query.Length, "FirstName as Column" + columnNo.ToString());
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "First Name";
paramField.CurrentValues.Add(paramDiscreteValue);
//Add the paramField to paramFields
paramFields.Add(paramField);
}
if (chbLastName.Checked)
{
columnNo++;
if (query.Contains("Column"))
{
query = query.Insert(query.Length, ", ");
}
query = query.Insert(query.Length, "LastName as Column" + columnNo.ToString());
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "Last Name";
paramField.CurrentValues.Add(paramDiscreteValue);
// Add the paramField to paramFields
paramFields.Add(paramField);
}
if (chbAddress.Checked)
{
columnNo++;
if (query.Contains("Column"))
{
query = query.Insert(query.Length, ", ");
}
query = query.Insert(query.Length, "Address as Column" + columnNo.ToString());
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "Address";
paramField.CurrentValues.Add(paramDiscreteValue);
//Add the paramField to paramFields
paramFields.Add(paramField);
}
if (chbPhone.Checked)
{
columnNo++;
if (query.Contains("Column"))
{
query = query.Insert(query.Length, ", ");
}
query = query.Insert(query.Length, "Phone as Column" + columnNo.ToString());
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "Phone";
paramField.CurrentValues.Add(paramDiscreteValue);
// Add the paramField to paramFields
paramFields.Add(paramField);
}
//if there is any remaining parameter, assign empty value for that
//parameter.
for (int i = columnNo; i < 5; i++)
{
columnNo++;
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "";
paramField.CurrentValues.Add(paramDiscreteValue);
//Add the paramField to paramFields
paramFields.Add(paramField);
}
crystalReportViewer1.ParameterFieldInfo = paramFields;
query += " FROM Customer" ;
return query;
}
}
I have DataGridView Control in windows application.
I load data and bind it to grid using above code.
private void LoadData()
{
clsData objData = new clsData();
DataTable dtTemp = new System.Data.DataTable();
dtTemp = objData.GetDatatable(" SELECT [ID],[CustomerName],[OrderQty],[Price],[POStatus],[Remarks],[EstdShipDate],[ActualShipDate],[IsShipped] FROM [tblPO] ");
dgPO.DataSource = null;
dgPO.DataSource = dtTemp;
}
where dgPO is DataGrdiView(DGV).
Now i want to update records in DGV when user leaves the row.
for it i have used RowLeave event of DGV.code is here
private void dgPO_RowLeave(object sender, DataGridViewCellEventArgs e)
{
int POId = Convert.ToString(dgPO.Rows[e.RowIndex].Cells[0].Value) == "" ? 0 : Convert.ToInt32(dgPO.Rows[e.RowIndex].Cells[0].Value);
string CustName = Convert.ToString(dgPO.Rows[e.RowIndex].Cells[1].Value);
int Qty = Convert.ToInt32(dgPO.Rows[e.RowIndex].Cells[2].Value);
decimal Price = Convert.ToDecimal(dgPO.Rows[e.RowIndex].Cells[3].Value);
string Status = Convert.ToString(dgPO.Rows[e.RowIndex].Cells[4].Value);
string Remarks = Convert.ToString(dgPO.Rows[e.RowIndex].Cells[5].Value);
string dtEsdt = Convert.ToDateTime(dgPO.Rows[e.RowIndex].Cells[6].Value).ToString("yyyy-MM-dd");
string dtActl = Convert.ToDateTime(dgPO.Rows[e.RowIndex].Cells[7].Value).ToString("yyyy-MM-dd");
bool Shipped = dgPO.Rows[e.RowIndex].Cells[8].Value == DBNull.Value ? false : Convert.ToBoolean(dgPO.Rows[e.RowIndex].Cells[8].Value);
string strQry = "";
if (POId > 0)
{
strQry = " UPDATE [tblPO] SET [CustomerName] = '" + PreString(CustName) + "',[OrderQty] = " + Qty + ",[Price] = " + Price + ",[POStatus] = '" + Status + "'";
strQry = strQry + ",[Remarks] = '" + PreString(Remarks) + "',[EstdShipDate] = '" + dtEsdt + "',[ActualShipDate] = '" + dtActl + "',[IsShipped] = '" + Shipped + "'";
strQry = strQry + " WHERE ID =" + POId;
}
else
{
strQry = " INSERT INTO [tblPO] ([CustomerName],[OrderQty],[Price],[POStatus],[Remarks],[EstdShipDate],[ActualShipDate],[IsShipped]) ";
strQry += " VALUES('" + PreString(CustName) + "'," + Qty + "," + Price + ",'" + PreString(Status) + "','" + PreString(Remarks) + "'";
strQry += " ,'" + PreString(dtEsdt) + "','" + PreString(dtActl) + "','" + Shipped + "')";
}
clsData objData = new clsData();
if (objData.ExecuteQuery(strQry))
{
LoadData();
}
}
When data is updated in DB, I refresh the DGV by calling LoadData method.
At this point, i get an error message like this.
"Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function"
I tried for available solution on SO and MSDN blogs,but they don't work for me
like these
1) http://social.msdn.microsoft.com/Forums/en/winformsdatacontrols/thread/f824fbbf-9d08-4191-98d6-14903801acfc
2) Click on any other cell while a cell of same row of datagridvew is in edit mode causes Operation is not valid reentrant call
3) InvalidOperationException - When ending editing a cell & moving to another cell
Help needed.
Thanks in advance !!
Answer:
private void dgPO_RowLeave(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.EndEdit();
//You code below
}
Suggestion: The alternative way
Did you try to use .RowValidating Event and .IsCurrentRowDirty Method?
private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
if (dataGridView1.IsCurrentRowDirty)
{
//Your code here
}
}
use the following check before applying your edit in the "RowLeave" or "EndEdit" method:
public void dgPO_RowLeave(object sender, DataGridViewCellEventArgs e)
{
if (!dgPO.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected)
return;
//...rest of your code to apply edit below...
}
This should work with any cell being edited.(the edit-code is not applied when losing focus; Typing Enter would suffice to apply the edit)