using datagridView, exception occurs for INSERT command, while deletion and updation are working perfectly in C# using access database [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Using save button in my form, all operations (update, delete) working perfectly except INSERT command. Help me out of this...
public partial class frmeditaccess : Form
{
string table = "master";
OleDbDataAdapter da;
OleDbCommandBuilder cb;
DataTable dt;
OleDbConnection conn;
string query;
public frmeditaccess()
{
InitializeComponent();
}
private void btload_Click(object sender, EventArgs e)
{
try
{
conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" + #"Data source= C:\Users\ViPuL\Documents\Visual Studio 2010\Projects\feedback#MERI\feedback#MERI\bin\feedback.mdb";
query = string.Format("SELECT * FROM {0}", table);
da = new OleDbDataAdapter(query, conn);
dt = new DataTable();
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("Failed due to " + ex.Message);
}
}
private void btsave_Click(object sender, EventArgs e)
{
try
{
cb = new OleDbCommandBuilder(da);
da.Update(dt); //here update, delete are working. Only, Insert throws exception of syntax error in INSERT command.
}
catch (Exception ex)
{
MessageBox.Show("Failed due to " + ex.Message);
}
}

This may be due to reserved keyword used as column name, try by specifying QuotePrefix and QuoteSuffix as below
cb = new OleDbCommandBuilder(da);
cb.QuotePrefix = "[";
cb.QuoteSuffix = "]";
da.Update(dt);

Related

Why the while loop is used in this database connection?

Currectly I am studying and learning and I just wanted to know some logic of this database connection in C#. I wanted to know why the while loop is used I means if I don't use it, will it affect the program or will the program run fine if I take it out. I just wanted to know is it wise to use it or just take it out from the program. Can someone please help me ?? Thank you
private bool filled;
public DataSet ds = new DataSet();
private void bnt_displaylog_Click(object sender, EventArgs e)
{
try
{
string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Elevator_Database.accdb;";
string dbcommand = "Select * from Log;";
OleDbConnection conn = new OleDbConnection(dbconnection);
OleDbCommand comm = new OleDbCommand(dbcommand, conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(comm);
conn.Open();
//MessageBox.Show("Connection Open ! ");
**while (filled == false)**
{
adapter.Fill(ds);
filled = true;
}
conn.Close();
}
catch (Exception)
{
MessageBox.Show("Can not open connection ! ");
string message = "Error in connection to datasource";
string caption = "Error";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result;
result = MessageBox.Show(message, caption, buttons);
}
database_listbox.Items.Clear();
foreach (DataRow row in ds.Tables[0].Rows)
{
database_listbox.Items.Add(row["Date"] + "\t\t" + row["Time"] + "\t\t" + row["Action"]);
}
}
That's just code that was written in a very unclear manner. The while loop will never loop at all. The loop body will either be executed once, or not at all, depending on the value of filled.
In other words, the code could have been written more clearly as:
conn.Open();
if( ! filled )
{
adapter.Fill(ds);
filled = true;
}
conn.Close();
But even then, the code is doing the wrong thing. Think about the case where filled is true. The code that's actually executed is:
conn.Open();
conn.Close();
and what's the point of doing that?
In any case, what the code actually does, either with while or if, is call adapter.Fill(ds) only the first time through. Given that, we should skip setting up the connection entirely when we don't make that call. And let's refactor the code to make it a bit more clear:
private bool filled = false;
public DataSet ds = new DataSet();
private void bnt_displaylog_Click(object sender, EventArgs e)
{
loadDisplayLog();
database_listbox.Items.Clear();
foreach (DataRow row in ds.Tables[0].Rows)
{
database_listbox.Items.Add(
row["Date"] + "\t\t" + row["Time"] + "\t\t" + row["Action"]
);
}
}
private void loadDisplayLog(object sender, EventArgs e)
{
if( filled ) return;
try
{
string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Elevator_Database.accdb;";
string dbcommand = "Select * from Log;";
OleDbConnection conn = new OleDbConnection(dbconnection);
OleDbCommand comm = new OleDbCommand(dbcommand, conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(comm);
conn.Open();
adapter.Fill(ds);
conn.Close();
filled = true;
}
catch (Exception)
{
MessageBox.Show("Can not open connection ! ");
string message = "Error in connection to datasource";
string caption = "Error";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result;
result = MessageBox.Show(message, caption, buttons);
}
}
There are still some issues with the exception handling in this code - will the connection be closed if adapter.Fill(ds); throws an exception? Oops. But I'll leave the rest as an exercise for the reader...

index was out of range. must be nonnegative and less than the size of the collection. parameter name: index [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Guys I really need for your help. I am getting an error for the above title. All trying to do is when datagridview is click it should display selected record into the text box as well as open it new form. Here is my code.
using System.Data;
using System.Data.SqlClient;
namespace DataGridview
{
public partial class FrmDataGrid : Form
{
SqlConnection con = new SqlConnection("ConnectionString");
public FrmDataGrid()
{
InitializeComponent();
}
private void FrmDataGrid_Load(object sender, EventArgs e)
{
try {
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM UserData";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
textBox1.Text = dataGridView1.SelectedRows[0].Cells["UserID"].Value.ToString();
textBox2.Text = dataGridView1.SelectedRows[1].Cells["FullName"].Value.ToString();
textBox3.Text = dataGridView1.SelectedRows[2].Cells["Username"].Value.ToString();
textBox4.Text = dataGridView1.SelectedRows[3].Cells["UserPassword"].Value.ToString();
textBox5.Text = dataGridView1.SelectedRows[4].Cells["UserRole"].Value.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
FrmUpdate FormUpdate = new FrmUpdate();
FormUpdate.ShowDialog();
}
}
}
You're trying to fetch 5 rows without even checking that 5 rows exists in the result of your db query. I think you're trying to fetch 5 columns of a row, so use the following code for your requirement:
textBox1.Text = dataGridView1.SelectedRows[0].Cells["UserID"].Value.ToString();
textBox2.Text = dataGridView1.SelectedRows[0].Cells["FullName"].Value.ToString();
textBox3.Text = dataGridView1.SelectedRows[0].Cells["Username"].Value.ToString();
textBox4.Text = dataGridView1.SelectedRows[0].Cells["UserPassword"].Value.ToString();
textBox5.Text = dataGridView1.SelectedRows[0].Cells["UserRole"].Value.ToString();
You are most likely selecting a row that is out of range, during one of these calls:
dataGridView1.SelectedRows[0]

attempted to read write protected memory. this is often an indication that other memory is corrupt [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have developed a desktop application using C# and sql server compact 3.5
I have import all necessary dll's
System.Data.SqlServerCe.dll
sqlceca35.dll
sqlcecompact35.dll
sqlceer35EN.dll
sqlceme35.dll
sqlceoledb35.dll
sqlceqp35.dll
sqlcese35.dll
And deploy it while it is running without any error on this PC when i install setup on client machine it will do insertion accurately in database.sdf and also retrieve data for auto-complete.
When I want to retrieve data from it to fill combo box or grid it will generate error
attempted to read write protected memory.
this is often an indication that other memory is corrupt
Note: if I install this setup on another pc which have VS 2008 on it will work fine without any error. Will I have to install something on the Client Pc?
I also try to build
in VS2008:
Tools->Options
Debugging->General
uncheck option "Suppress JIT optimization on module load"
but result is same.
Here is a class that I used for store and retrive data from db
class dataBase
{
private SqlCeDataAdapter ad;
private SqlCeCommand cmd;
private string StringdbFileName=("Data Source=" + System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\sp.sdf").Replace(#"file:\", "");
private SqlCeConnection coon;
public dataBase()
{
coon = new SqlCeConnection(StringdbFileName);
coon.Close();
}
public int ExecuteSQL(string Query)
{
try
{
coon.Open();
cmd = new SqlCeCommand();
cmd.Connection = this.coon;
cmd.CommandText = Query;
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
coon.Close();
}
}
public DataTable GetDataTable(string Query)
{
try
{
coon.Open();
DataTable dt = new DataTable();
cmd = new SqlCeCommand();
cmd.CommandText = Query;
ad = new SqlCeDataAdapter(Query,coon);
ad.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
coon.Close();
}
}
public void FillComboBox(string Query, string DisplayMember,string ValueMember, ComboBox cmb)
{
try
{
coon.Open();
DataTable dt = new DataTable();
cmd = new SqlCeCommand();
cmd.CommandText = Query;
ad = new SqlCeDataAdapter(Query, coon);
ad.Fill(dt);
cmb.DataSource = dt;
cmb.DisplayMember = DisplayMember;
cmb.ValueMember = ValueMember;
}
catch (Exception ex)
{
throw ex;
}
finally
{
coon.Close();
}
}
}
From my experience, this happens when you access the same SqlConnection from different threads.
SQL CE is not very thread-friendly.

What is the connection string if my database is host online, not in my local computer? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can WCF consuming data from database phpmyadmin?
I want to ask about the connection string that should i write at WCF. My database is host at phpmyadmin.
How should I write the connections string? if the database is using microsoft access or sqlserver that run at my computer, I done it already. Now, I'm curious if my database at phpmyadmin.
Honestly, I already asked this question in this forum yesterday. I say a big thanks to whom answer my question but I dont think that is a answer. I'm sorry for being stupid and don't understand what you said yesterday. If you get mad, you don't need to answer. thanks.
Out of the topic, this my WCF code.
public class Jobs : IJobs
{
SqlConnection conn = new SqlConnection("Data Source=127.0.0.1; Initial Catalog=mydatabase;User=ael;Password=123456;Integrated Security=False");
SqlDataAdapter da;
DataSet ds;
Data data = new Data();
List<Data> listdata = new List<Data>();
public DataSet Details()
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data", conn);
da.Fill(ds);
conn.Close();
return ds;
}
public Data GetDetails(int jobid)
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data where id = " + jobid, conn);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
data.userid = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
data.firstname = ds.Tables[0].Rows[0][1].ToString();
data.lastname = ds.Tables[0].Rows[0][2].ToString();
data.location = ds.Tables[0].Rows[0][3].ToString();
ds.Dispose();
}
conn.Close();
return data;
}
public List<Data> GetAllDetails()
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data", conn);
da.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
listdata.Add(
new Data
{
userid = Convert.ToInt32(dr[0]),
firstname = dr[1].ToString(),
lastname = dr[2].ToString(),
location = dr[3].ToString()
}
);
}
conn.Close();
return listdata;
}
}
this is the wpf
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
if (textbox1.Text.Trim().Length != 0)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
var x = jc.GetDetails(Convert.ToInt32(textbox1.Text));
if (x.userid != 0)
{
textbox2.Text = x.userid.ToString();
textbox3.Text = x.firstname;
textbox4.Text = x.lastname;
textbox5.Text = x.location;
}
else
MessageBox.Show("RecordNotFound ... !", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
MessageBox.Show("EnterID", "Message", MessageBoxButton.OK, MessageBoxImage.Warning);
}
private void button2_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
dataGrid1.ItemsSource = jc.Details().Tables[0].DefaultView;
}
private void button3_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
dataGrid1.ItemsSource = jc.GetAllDetails() ;
}
}
I already create a user at phpmyadmin, and use it at my WCF. but whenever I run, its show "login failed for user ael".
Is there something I need to change in the connection string?
thanks before.
If I understand correctly you need an example for the connection string.
So for the connection string format please see ConnectionsStrings.com
For example, if you are using the standard port and did not change it:
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Then you can to use the MySQL Connector (Namespace MySql.Data.MySqlClient downloadable here) and connect to the MySQL database programatically as explained in detail in this tutorial: Connection to the MySQL Server.

SqlDataAdapter.Update or SqlCommandBuilder not working

I have a form with a datagrid, which is populated wih data from a sqlserver database. The datagrid populates fine but I am having trouble posting back the changes made by the user, to the table in the sql database. My forms code is as follows:
public partial class frmTimesheet : Form
{
private DataTable tableTS = new DataTable();
private SqlDataAdapter adapter = new SqlDataAdapter();
private int currentTSID = 0;
public frmTimesheet()
{
InitializeComponent();
}
private void frmTimesheet_Load(object sender, EventArgs e)
{
string strUser = cUser.currentUser;
cMyDate cD = new cMyDate(DateTime.Now.ToString());
DateTime date = cD.GetDate();
txtDate.Text = date.ToString();
cboTSUser.DataSource = cUser.GetListOfUsers("active");
cboTSUser.DisplayMember = "UserID";
cboTSUser.Text = strUser;
CheckForTimeSheet();
PopulateTimeSheet();
}
private void CheckForTimeSheet()
{
string strUser = cboTSUser.Text;
cMyDate cD = new cMyDate(txtDate.Text);
DateTime date = cD.GetDate();
int newTSID = cTimesheet.TimeSheetExists(strUser, date);
if (newTSID != this.currentTSID)
{
tableTS.Clear();
if (newTSID == 0)
{
MessageBox.Show("Create TimeSheet");
}
else
{
this.currentTSID = newTSID;
}
}
}
private void PopulateTimeSheet()
{
try
{
string sqlText = "SELECT EntryID, CaseNo, ChargeCode, StartTime, FinishTime, Units " +
"FROM tblTimesheetEntries " +
"WHERE TSID = " + this.currentTSID + ";";
SqlConnection linkToDB = new SqlConnection(cConnectionString.BuildConnectionString());
SqlCommand sqlCom = new SqlCommand(sqlText, linkToDB);
SqlDataAdapter adapter = new SqlDataAdapter(sqlCom);
adapter.SelectCommand = sqlCom;
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Fill(tableTS);
dataTimesheet.DataSource = tableTS;
}
catch (Exception eX)
{
string eM = "Error Populating Timesheet";
cError err = new cError(eX, eM);
MessageBox.Show(eM + Environment.NewLine + eX.Message);
}
}
private void txtDate_Leave(object sender, EventArgs e)
{
CheckForTimeSheet();
PopulateTimeSheet();
}
private void cboTSUser_DropDownClosed(object sender, EventArgs e)
{
CheckForTimeSheet();
PopulateTimeSheet();
}
private void dataTimesheet_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
try
{
adapter.Update(tableTS);
}
catch (Exception eX)
{
string eM = "Error on frmTimesheet, dataTimesheet_CellValueChanged";
cError err = new cError(eX, eM);
MessageBox.Show(eM + Environment.NewLine + eX.Message);
}
}
}
No exception occurs, and when I step through the issue seems to be with the SqlCommandBuilder which does NOT build the INSERT / UPDATE / DELETE commands based on my gien SELECT command.
Can anyone see what I am doing wrong?
What am I missing?
You need to set the UpdateCommand instead of SelectCommand on update:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
The question is old, but the provided answer by#Anurag Ranjhan need to be corrected.
You need not to write the line:
adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
and enough to write:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
//remove the next line
//adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
The Sql update/insert/delete commands are auto generated based on this line
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
You can find the generated update sql by executing the line:
sqlBld.GetUpdateCommand().CommandText;
See the example How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visual C# .NET
The problem said by OP can be checked by reviewing the Sql Statement sent by the client in SQl Server Profiler.

Categories