C# School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a C# Expert!

Join 300,419 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,508 people online right now. Registration is fast and FREE... Join Now!




ACCESS and VC# application

 

ACCESS and VC# application, Last record and check box problems

daydr3am3r

23 Jun, 2009 - 02:44 PM
Post #1

New D.I.C Head
*

Joined: 10 Apr, 2009
Posts: 17


My Contributions
Hi

I'm working at an C# 2008 and MS ACCESS app and I encounter a few problems(I'm new to SQL and C#).

The first thing I wanna do is to select the last record from one table.
If I specify the record ID everything works fine but I don't know how to go to the last record.

CODE

string cl_cmd = @"select first_name,last_name,ID_Nod from cmmd WHERE ID_cmd = 5";


I tried to use IDENT_CURRENT('table') but it didn't work.


The second problem is adding the value from a check box intro a Yes/No field AND displaying the value of the Yes/No field using a check box.
I have a login table with 4 field ID, username, password and admin(Yes/No).
If I login as admin I have the possibility to change other's people right and data like password and admin rights.

The problem is how do I convert the value returned by the check box(true or false) so that I can insert it into my table when I want to update or add new users.

Here is the code for my FIND button:
CODE

private void btnFind_Click(object sender, EventArgs e)
        {
            try
            {
                for (int i = 0; i < mydset.Tables[0].Rows.Count; i++)
                {

                    if (Convert.ToInt32(mydset.Tables[0].Rows[i]["usrlg_ID"]) == Convert.ToInt32(txtID.Text))
                    {
                        txtUsrnm.Text = mydset.Tables[0].Rows[i]["username"].ToString();
                        txtPswd.Text = mydset.Tables[0].Rows[i]["password"].ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

This works fine if I don't try to getthe value from the "admin" field and display it as a checkbox(checked if is admin unchecked if not).

Also, when I try to update the data displayed, including the checkbox value I receive an "Update statement error":

CODE

private void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                /*
                 *  update process is also same since the update statement will not return any value
                 *  we will use Command object and inside sql statement as in delete sql statement you have to
                 *  use some variables, you have to update address and tel by using values in textboxes  
                 * */

                OleDbConnection mycon = new OleDbConnection(connectionstring);

                string sql = "update login set username = '" + txtUsrnm.Text + "' , password = '" + txtPswd.Text + "' where Student_ID = " + txtID.Text +"";
                OleDbCommand mycommand = new OleDbCommand(sql, mycon);
                mycon.Open();
                mycommand.ExecuteNonQuery();
                mycon.Close();
                MessageBox.Show("Record is successfully updated");

                //after update fill dataset and datagrid again
                string sql2 = "select * from login";
                OleDbDataAdapter adap = new OleDbDataAdapter(sql2, mycon);

                // DataSet should be cleared firstly
                mydset.Clear();
                adap.Fill(mydset);
                dgvUsr.DataSource = mydset.Tables[0];

                // Clear the textboxes also, since the record is updated
                txtID.Text = "";
                txtUsrnm.Text = "";
                txtPswd.Text = "";
                chkAdmin.Checked = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }



User is offlineProfile CardPM
+Quote Post


Jayman

RE: ACCESS And VC# Application

23 Jun, 2009 - 03:06 PM
Post #2

Student of Life
Group Icon

Joined: 26 Dec, 2005
Posts: 8,544



Thanked: 226 times
Dream Kudos: 500
Expert In: Everything

My Contributions
For your first question, you can easily get the max ID of a column by using a nested query. The inner query will get the MAX of the ID_cmd and return it to the outer query which will get the data you need.

CODE

string cl_cmd = @"select first_name,last_name,ID_Nod from cmmd WHERE ID_cmd = (select max(ID_cmd) from cmmd)";


For you second question, you don't need to convert anything. Just set a string to equal Yes/No depending on whether the CheckBox is checked/unchecked. Then insert the string value into your table. This can be done with a simple IF statement.

Example:
CODE
string checkboxValue = "";

if (CheckBox1.Checked)
   checkboxValue = "Yes";
else
   checkboxValue = "No";


Now update the table with the value stored in checkboxValue. Do the reverse when you read it back from the database and set the Checkbox.

What is the entire error message you get for your third question?
User is offlineProfile CardPM
+Quote Post

daydr3am3r

RE: ACCESS And VC# Application

24 Jun, 2009 - 05:55 AM
Post #3

New D.I.C Head
*

Joined: 10 Apr, 2009
Posts: 17


My Contributions
Thanks Jayman and sorry for the late reply. For my first question your solution worked perfect.
Howeve, for the second one nothing happened.
After setting the value of my string to Yes or No I used the string in the insert into statement and it didn't work. Could you please be mor explicit, maybe I didnt get it right.

And the error message is OleDB Connection error in UPDATE STATEMENT.
User is offlineProfile CardPM
+Quote Post

Jayman

RE: ACCESS And VC# Application

24 Jun, 2009 - 08:07 AM
Post #4

Student of Life
Group Icon

Joined: 26 Dec, 2005
Posts: 8,544



Thanked: 226 times
Dream Kudos: 500
Expert In: Everything

My Contributions
Post your revised code and lets see how you implemented the changes.
User is offlineProfile CardPM
+Quote Post

daydr3am3r

RE: ACCESS And VC# Application

24 Jun, 2009 - 08:34 AM
Post #5

New D.I.C Head
*

Joined: 10 Apr, 2009
Posts: 17


My Contributions

CODE

private void btnAdd_Click(object sender, EventArgs e)
        {
            OleDbConnection mycon = null;

            using (mycon = new OleDbConnection(connectionstring))
            {
                //mycon.Open();

                try
                {
                    //OleDbConnection mycon = new OleDbConnection(connectionstring);

                    string usr = txtUsrnm.Text;
                    string pswd = txtPswd.Text;
                    string checkboxValue = "";
                    if (chkAdmin.Checked)
                        checkboxValue = "Yes";
                    else
                        checkboxValue = "No";

                    string sql = "INSERT INTO login(username, password, admin) values" +
                                    "('" + usr + "','" + pswd + "','" + checkboxValue + "')";

                    OleDbCommand mycommand = new OleDbCommand(sql, mycon);
                    mycon.Open();

                    mycommand.ExecuteNonQuery();

                    mycon.Close();


                    string sql2 = "select * from login";
                    OleDbDataAdapter adap = new OleDbDataAdapter(sql2, mycon);


                    mydset.Clear();
                    adap.Fill(mydset);
                    dgvUsr.DataSource = mydset.Tables[0];

                    txtID.Text = "";
                    txtUsrnm.Text = "";
                    txtPswd.Text = "";
                    chkAdmin.Checked = false;
                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                //mycon.Close();
            }
        }

User is offlineProfile CardPM
+Quote Post

Jayman

RE: ACCESS And VC# Application

24 Jun, 2009 - 11:46 AM
Post #6

Student of Life
Group Icon

Joined: 26 Dec, 2005
Posts: 8,544



Thanked: 226 times
Dream Kudos: 500
Expert In: Everything

My Contributions
You should be using a Try/Catch to catch the errors when inserting/updating/deleting data into your database. Perhaps then you can get more verbose error messages that might indicate what you are doing wrong.

QUOTE
After setting the value of my string to Yes or No I used the string in the insert into statement and it didn't work.

What exactly do you mean it didn't work?
- no data in table?
- failed with error message?

Are you certain you have spelled the table and column names correctly in the Insert statement?
User is offlineProfile CardPM
+Quote Post

daydr3am3r

RE: ACCESS And VC# Application

24 Jun, 2009 - 12:42 PM
Post #7

New D.I.C Head
*

Joined: 10 Apr, 2009
Posts: 17


My Contributions
I'm sure I din't spell the column or the table name wrong.
The table name is login and the columns are username, password and admin.
I receive the same error message: OleDB connection error in INSERT INTO statement.

My database has 6 tables and I had no problem so far. Since this is the only table containing Yes/No field I'm assuming that the error is because of this.
I also tried inserting the checkbox value using On/Off, True/False, 1/0 and 0/-1(I've noticed that this are the values stored in ACCESS for Yes/No).
I even tried to return the value of the checkbox using chkBox.CheckState.
User is offlineProfile CardPM
+Quote Post

Jayman

RE: ACCESS And VC# Application

24 Jun, 2009 - 03:10 PM
Post #8

Student of Life
Group Icon

Joined: 26 Dec, 2005
Posts: 8,544



Thanked: 226 times
Dream Kudos: 500
Expert In: Everything

My Contributions
Ok, didn't realize Access handles it differently. You can use either True/False or 0/-1.

Make sure you remove the single quotes around the value being inserted for the Yes/No field.

CODE

string sql = "INSERT INTO login(username, password, admin) values" +
     "('" + usr + "','" + pswd + "'," + checkboxValue + ")";

User is offlineProfile CardPM
+Quote Post

daydr3am3r

RE: ACCESS And VC# Application

30 Jun, 2009 - 10:36 AM
Post #9

New D.I.C Head
*

Joined: 10 Apr, 2009
Posts: 17


My Contributions
Hi Jayman
Sry for the late reply. Thanks for all the help.
However, iti didn'
t work that way so I changed the field type to string and I added as validation rule "Yes" or "No".
After that I declared a string var and change its value when the checkbox was checked(Yes) or not(No).
Here is the code:
CODE

private void btnAdd_Click(object sender, EventArgs e)
        {
            OleDbConnection mycon = null;

            using (mycon = new OleDbConnection(connectionstring))
            {
                try
                {
                    string usr = txtUsrnm.Text;
                    string pswd = txtPswd.Text;
                    string checkboxValue;
                    
                    if (chkAdmin.Checked)
                        checkboxValue = "Yes";
                    else
                        checkboxValue = "No";

                    string sql = "INSERT INTO [login]([username], [password], [admin]) values" +
                                    "('" + usr + "','" + pswd + "','" + checkboxValue + "')";

                    OleDbCommand mycommand = new OleDbCommand(sql, mycon);
                    mycon.Open();

                    mycommand.ExecuteNonQuery();

                    mycon.Close();

                    string sql2 = "select * from login";
                    OleDbDataAdapter adap = new OleDbDataAdapter(sql2, mycon);

                    mydset.Clear();
                    adap.Fill(mydset);
                    dgvUsr.DataSource = mydset.Tables[0];

                    txtID.Text = "";
                    txtUsrnm.Text = "";
                    txtPswd.Text = "";
                    chkAdmin.Checked = false;
                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

Once again, thanks for your help.
User is offlineProfile CardPM
+Quote Post

programmer2u

RE: ACCESS And VC# Application

3 Jul, 2009 - 01:05 PM
Post #10

New D.I.C Head
*

Joined: 1 May, 2009
Posts: 8

HI PLEASE HELP ME WITH THE CODES WRITTEN BELOW
I WAS TRYING TO INSERT THE RECORDS FROM TWO TEXT BOXES TO ACCESS DB.
WELL THERE WERE NO ERRO BUT I STILL C`NT SEE THE VALUES IN DATABASE




void Button6Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbDataAdapter da;




string connect="Provider=Microsoft.jet.oledb.4.0;data source=.\\db1.mdb";
toolStripProgressBar1.Value=25;
OleDbConnection con = new OleDbConnection(connect);
con.Open();
DataSet ds1;
ds1=new DataSet();
//ds1.Tables.Add("r");
toolStripProgressBar1.Value=25;

string sql="select * from red";
da= new System.Data.OleDb.OleDbDataAdapter(sql,con);

System.Data.OleDb.OleDbCommandBuilder cb;
cb = new System.Data.OleDb.OleDbCommandBuilder( da );

da.Fill(ds1,"red");

int MaxRows = 0;
int inc = 0;
MaxRows = ds1.Tables["red"].Rows.Count;



//To add a record to the Dataset, you need to create a new Row
DataRow dr=ds1.Tables["red"].NewRow();

MaxRows = MaxRows + 1;
inc = MaxRows - 1;
MessageBox.Show(textBox2.Text);

//But the Row will not have any data.
//To add data to the row, the format is this:
dr[1]=textBox2.Text.ToString();
dr[2]=textBox3.Text.ToString();

toolStripProgressBar1.Value=75;


//Finally, you issue the Add command:
ds1.Tables["red"].Rows.Add(dr);
ds1.AcceptChanges();


//The only thing you need to do is tell it which Dataset holds
//all the records, and its name:

//da.Update( ds1, "Workers" );

da.Update(ds1,"red");

toolStripProgressBar1.Value=100;
con.Close();
}
}
}

User is offlineProfile CardPM
+Quote Post

daydr3am3r

RE: ACCESS And VC# Application

4 Jul, 2009 - 01:17 AM
Post #11

New D.I.C Head
*

Joined: 10 Apr, 2009
Posts: 17


My Contributions
Hi.

I'm still new to C# but why don't u try using an "INSERT INTO" statement instead od DataRow()?
User is offlineProfile CardPM
+Quote Post

noorahmad

RE: ACCESS And VC# Application

4 Jul, 2009 - 04:42 AM
Post #12

Webmaster
Group Icon

Joined: 12 Mar, 2009
Posts: 2,018



Thanked: 125 times
Dream Kudos: 1350
My Contributions
change your this code
C#.Net
if (chkAdmin.Checked)
checkboxValue = "Yes";
else
checkboxValue = "No";


C#.Net
 int i;
if (chkAdmin.Checked == true)
{
i = 1;
}
else
{
i = 0;
}


Hope it help You smile.gif
User is online!Profile CardPM
+Quote Post

daydr3am3r

RE: ACCESS And VC# Application

4 Jul, 2009 - 04:47 AM
Post #13

New D.I.C Head
*

Joined: 10 Apr, 2009
Posts: 17


My Contributions
Thanks for the help but I already tried that option.
Anyway I already made it work by using a string.
It's all described in one of my posts.
User is offlineProfile CardPM
+Quote Post

noorahmad

RE: ACCESS And VC# Application

4 Jul, 2009 - 04:52 AM
Post #14

Webmaster
Group Icon

Joined: 12 Mar, 2009
Posts: 2,018



Thanked: 125 times
Dream Kudos: 1350
My Contributions
Glad to Solve Your Problem.
User is online!Profile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/7/09 11:49PM

Live C# Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month