Welcome to Dream.In.Code
Getting C# Help is Easy!

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




Stuck with writing to a Db

 
Reply to this topicStart new topic

Stuck with writing to a Db, Repeating error, I cannot clear

Premier2k
post 29 Aug, 2008 - 02:54 PM
Post #1


New D.I.C Head

*
Joined: 26 Aug, 2008
Posts: 22


My Contributions


Hi all,

I am going to pull my hair out soon with this. I am trying to write a record to the database. As far as I know, it's being written to the DataSet and then trying to update the Db but I'm getting an error keep arising.

Object reference not set to an instance of an object.

It seems that the value dRow is not being updated but I just cannot work out why.

The main screen form here; (It's probably really messy for you guys but I'm learning and trying to keep it clean!)

CODE

namespace Pok3r_1._0
{
    public partial class mainScreen : Form
    {
        public mainScreen()
        {
            InitializeComponent();
        }
        
        public static System.Data.SqlClient.SqlConnection con;
        public static System.Data.SqlClient.SqlDataAdapter da;
        public static DataSet ds1 = new DataSet();
        public static int MaxRows = 0;
        public static int inc = 0;
        
        private void btnGo_Click(object sender, EventArgs e)
        {
            if (radioAdd.Checked)
            {              
                //Open add player form (addplayer.cs)
                Form.ActiveForm.Hide();
                add.Show();
            }

            else if (radioDelete.Checked)
            {
                //Open the delete player form (delplayer.cs)
                Form.ActiveForm.Hide();
                del.Show();
            }
            else
            {
                //Open the view player form (viewplayer.cs)
                Form.ActiveForm.Hide();
                view.Show();
            }
        }

        private void MainScreen_Load(object sender, EventArgs e)
        {          
            con = new System.Data.SqlClient.SqlConnection();
            con.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Pok3rv1.mdf;Integrated Security=True;User Instance=True";
            con.Open();

            string sql = "SELECT * From player_info";
            da = new System.Data.SqlClient.SqlDataAdapter(sql, con);

            da.Fill(ds1, "Pok3rv1DataSet");
            DataRow dRow = mainScreen.ds1.Tables["Pok3rv1DataSet"].Rows[inc];
            MaxRows = ds1.Tables["Pok3rv1DataSet"].Rows.Count;

            con.Close();
        }
    }
}



Then the Add Player screen;

CODE

namespace Pok3r_1._0
{
    public partial class addplayer : Form
    {
        public addplayer()
        {
            InitializeComponent();
        }

        public void btnBack_Click(object sender, EventArgs e)
        {
            mainScreen main = new mainScreen();
            
            //Add IF getting whether there IS any information in the text boxes
            if (firstName.Text == "" && lastName.Text == "" && nickName.Text == "")
            {
                //Hide the form
                Form.ActiveForm.Hide();
                //Show the main menu
                main.Show();
            }
            else
            {
               //Show a message box asking the user to confirm that they want to go back
                DialogResult result =  MessageBox.Show("Are you sure you want to go back? The information you have entered will not be saved", "Confirm",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                //Check the button the user clicked
                if (result == DialogResult.Yes)
                {
                
                    //User clicked Yes, so clear the boxes
                    firstName.Clear();
                    lastName.Clear();
                    nickName.Clear();

                    //Hide the form
                    Form.ActiveForm.Hide();
                    //Show the main menu
                    main.Show();
                }
                else
                {
                    //Just close this message box
                }
            }  
        }

        public void btnContinue_Click(object sender, EventArgs e)
        {
            System.Data.SqlClient.SqlCommandBuilder cb;
            cb = new System.Data.SqlClient.SqlCommandBuilder(mainScreen.da);

            //Store the text entries as strings in the given variables
            string first_name = firstName.Text;
            string surname = lastName.Text;
            string nick_name = nickName.Text;

            //Check that first name and surname are not blanked as the Db will not accept NULL values
            if (first_name == "" || surname == "")
            {
                MessageBox.Show("Please ensure at least first name and surname boxes are filled in", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {                
                //Test that information is stored correctly
                //MessageBox.Show(first_name);
                //MessageBox.Show(surname);
                //MessageBox.Show(nick_name);

                DataRow dRow = mainScreen.ds1.Tables["player_info"].NewRow();
                dRow[1] = firstName.Text;
                dRow[2] = lastName.Text;
                dRow[3] = nickName.Text;

                mainScreen.ds1.Tables["player_info"].Rows.Add(dRow);

                mainScreen.MaxRows = mainScreen.MaxRows + 1;
                mainScreen.inc = mainScreen.MaxRows - 1;

                mainScreen.da.Update(mainScreen.ds1, "player_info");
            }
        }

        public void addplayer_Load(object sender, EventArgs e)
        {
            //Clear the text boxes when the player enters the form
            firstName.Text = "";
            lastName.Text = "";
            nickName.Text = "";
        }
    }
}


The app runs fine right up until I enter some details in the add player screen and click continue, thats when I then get the error message Object reference not set to an instance of an object.
As i said, I have stepped through the code and it seems that dRow is what is causing the problem and is remaining at NULL.
The line causing the problem is in the addplayer code;

DataRow dRow = mainScreen.ds1.Tables["player_info"].NewRow();

Can anyone help with this?

Thanks in advance all!

Premier2k

This post has been edited by Premier2k: 29 Aug, 2008 - 02:56 PM
User is offlineProfile CardPM

Go to the top of the page

baavgai
post 29 Aug, 2008 - 03:44 PM
Post #2


Dreaming Coder

Group Icon
Joined: 16 Oct, 2007
Posts: 1,962



Thanked 96 times

Dream Kudos: 475

Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions


In addplayer, here:
CODE

DataRow dRow = mainScreen.ds1.Tables["player_info"].NewRow();


You're relying on a global ds1 to have the table you're referencing. However, you never loaded DataTable "player_info", you loaded "Pok3rv1DataSet":
CODE

da.Fill(ds1, "Pok3rv1DataSet");


There are numerous design warnings here. Two basic things, statics bad and ShowDialog good. This business of going back to main is an issue. You'd be better off just creating and closing your dialogs in the typical manner.

You might also consider placing the data manipulation code in it's own class and using typed DataSets.

Hope this helps.
User is offlineProfile CardPM

Go to the top of the page

Premier2k
post 30 Aug, 2008 - 02:16 AM
Post #3


New D.I.C Head

*
Joined: 26 Aug, 2008
Posts: 22


My Contributions


Hi baavgai.

OK I have changed the code in the addplayer.cs and that seems to work ok. So thanks for your help with!

I'm not sure of the difference between static and ShowDialog but I'll have a look into that and see where my code can be improved.

As for,
QUOTE
You might also consider placing the data manipulation code in it's own class and using typed DataSets.

What do you mean by this? I'm not sure I understand.

Thanks for all your help!

Premier2k
User is offlineProfile CardPM

Go to the top of the page

baavgai
post 30 Aug, 2008 - 03:40 AM
Post #4


Dreaming Coder

Group Icon
Joined: 16 Oct, 2007
Posts: 1,962



Thanked 96 times

Dream Kudos: 475

Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions


This is a pretty good intro to Typed DataSets. Essentially, with a database connection Visual Studio will write all the basic code for you. Even if you don't like code writers, the Typed DataSet alone is a useful tool.

As to a manager style class, consider this:
csharp

using System;
using System.Data;
using System.Data.SqlClient;

namespace Pok3r_1._0 {
public class DataManager {
private SqlConnection GetConnection() {
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Pok3rv1.mdf;Integrated Security=True;User Instance=True";
return con;
}

private SqlDataAdapter GetDaPlayerInfo() {
string sql = "SELECT * From player_info";
SqlDataAdapter da = new SqlDataAdapter(sql, GetConnection());
new SqlCommandBuilder(da);
return da;
}

public DataTable GetPlayerInfo() {
DataTable dt = new DataTable();
GetDaPlayerInfo().Fill(dt, "player_info");
return dt;
}

public int UpdatePlayerInfo(DataTable dt) {
SqlDataAdapter da = GetDaPlayerInfo();
return da.Update(dt);
}
}
}


Notice, GetConnection() isn't public. All the methods directly relating to talking to a data source are private, only the data sets are exposed. Not only is everything in one place, but if we ever have to change databases, the rest of the code needn't know.

Now, for updating:
csharp

DataManager dm = new DataManager();
DataTable dt = dm.GetPlayerInfo();
DataRow dRow = dt.NewRow();
dRow[1] = firstName.Text;
dRow[2] = lastName.Text;
dRow[3] = nickName.Text;
dt.AddRow(dRow);
dm.UpdatePlayerInfo(dt);


This works much better with typed datasets, as empty datasets still have structural meaning. If you want to maintain a global copy of the dataset, make the DataManager a singleton and maintain data.

e.g.
csharp

public class DataManager {
private static DataManager instance = new DataManager();
public static DataManager Instance { get { return instance; } }
private DataManager() { }

DataTable playerInfo = null;

public DataTable GetPlayerInfo() {
if (playerInfo==null) {
playerInfo = new DataTable();
GetDaPlayerInfo().Fill(playerInfo, "player_info");
}
return playerInfo;
}
}


I know, that's a lot to digest. Theres really a ton of info out there on this stuff. Happy googling. wink2.gif

Hope this helps.

This post has been edited by baavgai: 30 Aug, 2008 - 03:41 AM
User is offlineProfile CardPM

Go to the top of the page

Premier2k
post 30 Aug, 2008 - 12:14 PM
Post #5


New D.I.C Head

*
Joined: 26 Aug, 2008
Posts: 22


My Contributions


Thats fantastic baavgai!

I'm not sure how all that works yet, but I can pick through the code and suss it out.
That gives me something to get my teeth into! I shall look into that.

Incidently I have just ordered Microsoft® Visual C#® 2008 Step by Step (PRO- Step by Step Developer) by John Sharp from Amazon so I'm hoping that will provide me with additional help.

Many thanks again for your help baavgai!
It's great to be able to come on a site and have someone take time out to help beginners.

Premier2k (Paul)

User is offlineProfile CardPM

Go to the top of the page

Fast ReplyReply to this topicStart new topic
Time is now: 11/22/08 07:57AM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month