Error in list box

mustish1
mustish1 used Ask the Experts™
on
Can you please help me in that error?
Error in List Box[code]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace InsertUpdateDel
{
    public partial class Form1 : Form
    {
        SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Lenovo\Documents\Visual Studio 2012\Projects\InsertUpdateDel\InsertUpdateDel\Database1.mdf;Integrated Security=True;User Instance=True");
        SqlCommand cmd = new SqlCommand();
        SqlDataReader sd;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
                cmd.Connection = cn;
                loadlist();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (txtID.Text != "" & txtName.Text != "")
            {
                cn.Open();
                cmd.CommandText = "Insert into info(id, name) values ('" +txtID.Text+"', '" +txtName.Text+"')";
                cmd.ExecuteNonQuery();
                cmd.Clone();
                MessageBox.Show("Record Inserted", "Programming");
                cn.Close();
                txtID.Text="";
                txtName.Text="";
                loadlist();
            }
        }
        private void loadlist()
        {
            listBox1.Items.Clear();
            listBox2.Items.Clear();
            cn.Open();
            cmd.CommandText = "select * from info";
            sd = cmd.ExecuteReader();
            if (sd.HasRows)
            {
                while (sd.Read())
                {
                    listBox1.Items.Add(sd[0].ToString());
                    listBox2.Items.Add(sd[0].ToString());
                }
        }
        cn.Close();
        }

        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListBox 1 = sender as ListBox;
            //if (1.SelectedIndex != -1)
            {
                //listBox1.SelectedIndex = 1.SelectedIndex;
                //listBox2.SelectedIndex = 1.SelectedIndex;
        }
       
        }
    }
}
/code]
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Ryan ChongSoftware Team Lead

Commented:
1 is invalid object name, try use like yourObject, yourObject1, or myList1, etc instead!

Commented:
Ryan is correct - you can't use numbers as your variable names. If you could, then there would be tons of confusion. Imagine a simple math problem like:

i = 1 + 1;

Are you adding 1 + 1 to get 2 or are you adding two instances of your ListBox together?

So variable names should have some kind of letter or character to uniquely identify it within that scope.

Also, a couple of personal recommendations:

#1. When casting, use the parentheses to cast, like this:
ListBox listBox = (ListBox)sender;

...instead of the "as" operator:
ListBox listBox = sender as ListBox;

They both do VERY similar things but the parentheses approach will always give you an error if it's not a valid cast for some reason. For example, if "sender" was somehow a Form instead of a ListBox, you'd get an error at runtime if you tried to do (ListBox)sender. This is a good thing - you WANT to be notified when errors occur.

When you use the "as" approach, then if it's not a valid cast, .NET will try to assign a null value instead (if possible) instead of throwing an error. So instead of seeing an error about an invalid cast, your code might continue to execute as if everything is fine, but then when you try to access that value, it would give you a null reference error, which is often WAY more confusing later on ("How can 'sender' possibly be null?").

So if there's going to be a problem, it's better to be notified about it at the time that it occurs so you know exactly where to fix the problem. So always try to use () for casting.

#2. Make use of "var" to simplify your code. This:
ListBox listBox = (ListBox)sender;
int idx = listBox.SelectedIndex;

...is exactly the same as:
var listBox = (ListBox)sender;
var idx = listBox.SelectedIndex;

The "var" keyword is just a shortcut for the compiler. When you build your project, the compiler will go through and see "var" and then it will look at the VALUE to figure out what type it should use. For example, listBox.SelectedIndex is always an integer, so the compiler will replace the "var" with "int" when it's building the code.

Similarly, when you explicitly cast a value, the compiler sees that and says (ListBox)sender should always be a ListBox value, so the "var" on that line should be ListBox.

Every once in a while, you might need to explicitly set the type, but in most cases, the "var" shortcut will save you some keystrokes and speed up your coding.

Author

Commented:
This code runs fine in another program but i got error when i use it.
screenshot2.JPG
Software Team Lead
Commented:
that was a "I" instead of "1" ?
Ryan ChongSoftware Team Lead

Commented:
try rebuild your solutions and see if there's any error detected?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial