By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,963 Members | 1,261 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,963 IT Pros & Developers. It's quick & easy.

Update a list box

P: 53
Hello All,


I have a list of items in the listbox.(The items to the list box were added from the textbox eg ( listBox1.Items.Add(textBox1.Text)), Now If I have to alter the Listbox eg: If there is an item called Electricity in the listbox and now the user decides to replace Electriciy with an Item called Food by typing in the textbox how do I do this?? Thank you all....I am working on VS 2008 Winform.
Feb 9 '09 #1
Share this Question
Share on Google+
62 Replies


P: 12
use KeyValuePair class:
int key=someNo.
String value="value".
KeyValuePair<int,String> kvp=new KeyValuePair<string,string>(key,value);


for all the item, create above object(remember key should be unique), where value will represent the string to display, like "Electicity" etc.

now if user select an item. then get the selected item and change the value to new value or replace the old key value pair item with new one.
Feb 10 '09 #2

P: 59
The key value pair is a good suggestion. However, you may also use the item index property which is also unique for each item. There may be number of 'electricity' items with different indexes. To edit you may assign the edited test like:

Expand|Select|Wrap|Line Numbers
  1. lstBoc.Items[6].Text="New Electricity";
Regards
Feb 10 '09 #3

P: 12
my earlier given solution is bit complex. i forgot the way babai28 has suggested :)

any way do in following way:
int index = listBox1.SelectedIndex;
listBox1.Items[index] = "new_val";
Feb 10 '09 #4

P: 53
I tried your solution like this:

int index = listBox1.SelectedIndex;
listBox1.Items[index] = textBox1.Text;

But as soon as I select an item in the list box and try to feed a new value in the textbox1 it shows me this error:

An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll. Thank you all
Feb 10 '09 #5

P: 53
I tried your solution like this:

int index = listBox1.SelectedIndex;
listBox1.Items[index] = textBox1.Text;

But as soon as I select an item in the list box and try to feed a new value in the textbox1 it shows me this error:

An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll. Thank you all
Feb 10 '09 #6

P: 12
above give code will trigger listBox1_SelectedIndexChanged event so be careful.

i think you are putting this code
in listBox1_SelectedIndexChanged event. that is why it is calling this same the same code again and again. but i think in your problem you should put the code in textbox's text change event.
Feb 11 '09 #7

P: 16
try this

listBox1.Items[listBox1.SelectedIndex] = textBox1.text;
Feb 11 '09 #8

P: 53
Hi , I tried doint that, Before I even enter anything in the textbox and click on Save (so tht it saves in the Listbox) it says Index is not valid,because its taking -1 as the index.

I need to enter few Items in the textbox so that it is saved in my Listbox and then later I should be able to replace an item in the Listbox by entering new value in the TextBox , giving me error , please help...
Feb 11 '09 #9

P: 59
First tell me how are you handling the events.
What I mean is, how are you editing a particular item in the listbox.
Suppose your listbox displays three items

Electricity
Water
House

Now, you want to change the "House" text to "Bedroom". How do you expect the user to achieve this? Will he be double clicking it? Or will there be a separate button called "Edit" which when clicked after selecting the item "House" will bring the textbox before you?
Until you tell this it would be difficult to answer.
The next thing is the selectedItem.Index property is returning -1 as there is actually no item selected. You need to handle this by putting an if condition:
Expand|Select|Wrap|Line Numbers
  1. if(lstBox.SelectedItems.Count!=0)
  2. {
  3.        //put your code here
  4. }
Feb 12 '09 #10

P: 53
I have a Listbox, Textbox and a Combobox on the form. Suppose user enters House in the textbox then I am copying the House text from the textbox to Listbox and Combobox. Like this if the user enters
House
Electricity
Food.
Then I copy each one to the Listbox and also copying the items to the Combobox.
Now the user changes his mind and wants to update Electricity as Energy,The user double clicks on the Electricity ( in the listbox) then enters Energy in the Textbox. I want that change to happen in the listbox as well as Combobox.

I am really new to .NET, Hence my questions might be silly..I am trying to learn stuff, so please help.

Also is there any way I can copy the text in the textbox to multiple combobox??
if i do combobox1.Items.Add(textbox1.text); it copies only to combobox1, but I have multiple combobox ie, combobox1,combobox2 ......comboboxn.

Thanks a lot.........
Feb 12 '09 #11

P: 59
Fair Enough. I would suggest the following design:
Just write the code as it is:
declare a class level variable:
Expand|Select|Wrap|Line Numbers
  1. int globalIndex = -1;
Now,
Handle the mouse double click event of the list box as follows:

Expand|Select|Wrap|Line Numbers
  1. private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
  2.         {
  3.             if (listBox1.SelectedItems.Count != 0)
  4.             {
  5.                 globalIndex = listBox1.SelectedIndices[0];
  6.                 textBox1.Text = listBox1.SelectedItems[0].ToString();
  7.                 textBox1.SelectAll();
  8.             }
  9.         }
Next handle the edit button click event as follows:
Expand|Select|Wrap|Line Numbers
  1. private void button1_Click(object sender, EventArgs e)
  2.         {
  3.             if (textBox1.Text != String.Empty)
  4.             {
  5.                 listBox1.Items[globalIndex] = textBox1.Text;
  6.                 comboBox1.Items[globalIndex] = textBox1.Text;
  7.                 textBox1.Clear();
  8.             }
  9.             else
  10.                 MessageBox.Show("Please put a value");
  11.         }

The result:
1) The form looks like this in the beginning:refer First Pic of the Attachment
2) After double clicking the item Tap: refer Second Image of the attachment
3) I replaced the textBox Text witht the text "Cooler" and that gets reflected in the combobox and the listbox as well as in the third pic :)
Check if this is exactly what you want. You may make slight changes in the design to suit your specific requirement.
Attached Images
File Type: jpg firstPic.jpg (8.6 KB, 290 views)
File Type: jpg Second pic.jpg (9.3 KB, 267 views)
File Type: jpg Third Pic.jpg (9.3 KB, 559 views)
Feb 12 '09 #12

P: 59
Regarding your question of copying in multiple combo box, you yourself know the answer.

comboBox1.Items.Add(textBox1.Text);
comboBox2.Items.Add(textBox1.Text);
comboBox3.Items.Add(textBox1.Text);
comboBox4.Items.Add(textBox1.Text);
comboBox5.Items.Add(textBox1.Text);
comboBox6.Items.Add(textBox1.Text);
comboBox7.Items.Add(textBox1.Text);
comboBox8.Items.Add(textBox1.Text).
.
.
.
.
comboBoxn.Items.Add(textBox1.Text);

Even if you put a hundred comboBoxes I guess not CLR will raise its voice :)

Happy .Netting.
Feb 12 '09 #13

P: 53
Hi,
I did try, I am sorry to say again its not working, I dont know where I am going wrong, when I double click on the Listbox item I guess its not entering the event.

Here is my code:

private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (listBox1.SelectedItems.Count != 0)
{
globalindex = listBox1.SelectedIndices[0];
textBox1.Text = listBox1.SelectedItems[0].ToString();
textBox1.SelectAll();
}
}


private void button2_Click(object sender, EventArgs e) //SAVE BUTTON
{
if (textBox1.Text == String.Empty)
{
panel1.Visible = true;
}



else if (textBox1.Text != String.Empty)
{

string itemToAdd = textBox1.Text;
listBox1.Items.Add(itemToAdd);

}
}

Sorry for the trouble,Thanks a lot for the hlep..
Feb 12 '09 #14

P: 53
Hi,
Ignore the previous messgae...It worked............thanks a lot lot ....
Thaks a lot for your help, It worked, It worked when I created a seperate Modify button other than my SaveButton which intially saves items in the list box. When the user wants to modify the listbox, I double click on the item in the listbox and then use Modify button in order to update. If I try to do the same usign only SaveButton, since the intial globalindex will be -1, it gives me error.
But seperate buttons are working ,thanks a lot...

I have few more questions, Now I want to enter the listbox items to the database table, I have no clue how to do this, Do i ceate a connection intially by creating DataProvider object and Generate DataSet object and then try to put the listbox items in the Database table????? Give me some ideas so that I can start working around...
Feb 12 '09 #15

P: 53
Thanks a lot......Please look at my next reply and give me some idea....
Feb 12 '09 #16

P: 59
First tell me what is your data base?
Is it SQL or Access Database file or something else?
.Net offers a number of ways to perform Data Base operation. You may go for the DataAdapter and Dataset way. But since the way you are folllowing is least suited for data binding operation, I sugget you to go for connected way of dataBase operation. Go for a command object that would add the newly added item to the database.
I will only be able to help you after you tell me about the database (including table and all) structure you are following.

Regards,
Siddhartha
Feb 13 '09 #17

P: 53
Hello Siddharth,

Thanks a lot for your help:

Right now what I am doing is :

I have a text box, When I enter items in textbox like Food, and click on Save button it copies it to Listbox, and If I wish to change Food Item to restaurant,I double click on Food(in the listbox) and Food appears in the Textbox and I can change Food to Restaurant(The Logic is as you had suggested previously).I am attaching the code here.

private void button2_Click(object sender, EventArgs e) //SAVE BUTTON
{
if (textBox1.Text == String.Empty)
{
panel1.Visible = true;
}



else if (textBox1.Text != String.Empty && globalindex == -1 )
{

string itemToAdd = textBox1.Text;
listBox1.Items.Add(itemToAdd);
textBox1.Text = String.Empty;

}

else if (globalindex != -1)
{
listBox1.Items[globalindex] = textBox1.Text;

textBox1.Clear();
}



}

----------
Double clicking event on Listbox

private void listBox1_DoubleClick(object sender, System.EventArgs e)
{
if (listBox1.SelectedItems.Count != 0)
{
globalindex = listBox1.SelectedIndices[0];
textBox1.Text = listBox1.SelectedItems[0].ToString();

}
}


Now my next thing is When I click on Save button the Items shoule as well go the Database table(along with the Listbox which is already done).

The Database I am using is SQL Server 2005

Table Name : Category
Columns:
Category Id --Primary Key--type Int--Not Null (Category Id will automatically incriment the numbers 1,2 3.....as I enter stuff in the table.

Category Name: This column should have the Items which is entered in the textbox( When I click on Save the Item should be transfered to CategoryName column)


DateCreated: Should have the date when the used enters the CategoryName.

I dont know how to Create Database connection
I was refering to this website:
http://msdn.microsoft.com/en-us/library/ms973824.aspx

I have not tired it though...
In that one of the step is to Drag and Drop "generate DataSet "Control Under Data(toolbox). I was not able to find the "Generate Data Set toolbox"

I am using VS 2008.

I know its too lengthy to read,but since I am new to VS and C# I need some guidance like how to go with this...Thanks a lot for your help Siddharth.
Feb 13 '09 #18

P: 59
Hi,
Reading long replies is not a problem.! :)
Well, from what ever I understood from your reply I concluded the following things:
1) You want to maintain a list of categories in the database.
2) You want to provide the add, edit and delete functionalities using a list box control.
3) You store the data in a table called Category which has an auto incremeting primary key.
If my understanding is correct, then I don't think there is a need for updating the added items in the list box. You may update it directly in the data base and reshow the table afresh at the front end. Why do you want to update the UI and the data base separately?
You may follow the following techniques:
1) Bind the list box to the table and then do the add/edit/delete operation in the db itself. This will automatically get reflected in the listbox.
2) Another more handy approach (if the table is not too big) is to write code to show records in the list box directly from the db table and every time you perform an operation (add/edit/delete) in the database just call the method of redisplaying the data afresh in the front end.

Always remember, there is no single approach to a problem statement. A solution which is good in one case may be the worst in another case. Its the developer's job to decide which solution will be best suited.

You may update the database using any of the followng ways:
1) Writing simple stored procedures.
2) Writing parameterized query.
3) Firing constructed query from the front end (Not recommended).

Whenever you want to edit or delete a particular item you will need to have its Category_Id so that you may write a db command like:
"Delete from category where category_id=2"
For this I suggest storing the Category_Id in the tag property of the listBox item.

Writing connection string and all won't be a trouble if you have internet. Just search in google about the things I have suggested. I am sure you will get something useful. Let me know if my post helps.
All the best and happy .Netting.

Regards,
Siddhartha
Feb 16 '09 #19

P: 59
This is a good link.
Feb 16 '09 #20

P: 53
Hello Siddharth,

Thanks for the reply, Your answers are really helping me a lot..Thanks for your patience...

I was having a problem on stored procedure

When I click on my Save button( which saves the items in the textbox to Listbox as well as Database column) , in order to store in the database I am calling a stored procedure in my SQL Server 2005 database. Here is how I am doing.

void SavetoDB()
{
SqlCommand command = new SqlCommand("databaseinsert", connection);
command.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("@categoryname", SqlDbType.NVarChar, 50, "categoryname");
SqlParameter p2 = new SqlParameter("@datecreated", SqlDbType.DateTime, 50, "datecreated");
command.Parameters.Add(p1);
command.Parameters.Add(p2);


command.Parameters[0].Value= textBox1.Text;

command.Parameters[1].Value = DateTime.Now;

int i = command.ExecuteNonQuery();

}

When I call the stored procedure using above code, The database will have only the 1st letter of the textBox1.Text item( for example if I enter Food in my textbox1.txt, the database get only F)...I dont the problem,tried a lot..

Here is my Stored procedure:

create proc databaseinsert(@categoryname nvarchar,@datecreated datetime)
as insert into Category(categoryname,datecreated)
values (@categoryname,@datecreated);


My table Name: Category
Columns
categoryname
categoryid
datecreated.

categoryid incriments automatically.

Thanks a lot Siddharth...
Feb 16 '09 #21

P: 59
This is strange :)
Please check with the length of the CategoryName field. If you don't understand what I mean then please right click on the table in the business Studio and click create script. paste the script here. I guess you have made the length of the field 1. That is why SQL is taking only the first character and curtailing the rest of the text.
This may be a possibility, let me know if I am right.

Regards,
Siddhartha
Feb 17 '09 #22

P: 53
when i click on Script Action to new query window it gives me a messages "There is not action to be Scripted". :(

I dont know how to check for the lenght of categoryname field.
but when i right click on columnname(categoryname) it says nvarchar(50).


And also I wanted to copy the categoryname in my database column to the Listbox as soon as the form loads. I am not sure how to do databinding for listbox with DataAdapter and Dataset so that I can copy the categoryname to the listbox.Can you please help on this ...Thanks a lot again
Feb 17 '09 #23

P: 59
Add the efollowing user directive :
Expand|Select|Wrap|Line Numbers
  1. using System.Data.SqlClient;
At the class level declare a dataSet
Expand|Select|Wrap|Line Numbers
  1.  DataSet ds = new DataSet();
In the form load event add the following code:
Expand|Select|Wrap|Line Numbers
  1. SqlDataAdapter da = new SqlDataAdapter("Select * from category", finConnection);//Replace finConnection with your connection object
  2.             listBox1.Items.Clear();
  3.             try
  4.             {
  5.                 ds.Clear();
  6.                 da.Fill(ds, "Category");
  7.                 foreach (DataRow drow in ds.Tables["Category"].Rows)
  8.                 {
  9.                     listBox1.Items.Add(drow["CategoryName"]);
  10.                 }
  11.             }
  12.             catch (Exception ex)
  13.             {
  14.                 MessageBox.Show(ex.Message);
  15.             }
See if this is working.
Feb 17 '09 #24

P: 59
I see you will be having a tough time tying to edit items this way.
May be you switch to some different control. Or you go for data binding alternative.
Search in the internet for data binding in a listBox. the above solution i suggested will only be good for displaying the data in the listBox.

Regards,
Siddhartha
Feb 17 '09 #25

P: 59
For binding try this:

Expand|Select|Wrap|Line Numbers
  1. SqlDataAdapter da = new SqlDataAdapter("Select * from category", finConnection);//Replace finConnection with your connection object 
  2.           listBox1.Items.Clear();
  3.             try
  4.             {
  5.                 ds.Clear();
  6.                 da.Fill(ds, "Category");
  7.                 listBox1.DataSource = ds.Tables["Category"];
  8.                 listBox1.DisplayMember = "CategoryName";                
  9.             }
  10.             catch (Exception ex)
  11.             {
  12.                 MessageBox.Show(ex.Message);
  13.             }
But remember, once you bind the data, you will not be able to update the binded data in the Front end UI, You will need to update the data in the binding dataset, which will be reflected in the UI.

Regards,
Siddhartha
Feb 17 '09 #26

P: 59
Since you have data bounded the listBox your listBox Double Click Event is to be handled like:

Expand|Select|Wrap|Line Numbers
  1. private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
  2.         {
  3.             if (listBox1.SelectedItems.Count != 0)
  4.             {
  5.                 globalIndex = listBox1.SelectedIndices[0];
  6.                 textBox1.Text = ds.Tables["Category"].Rows[globalIndex]["CategoryName"].ToString();
  7.                 textBox1.SelectAll();
  8.             }
  9.         }
All the best.!
Feb 17 '09 #27

P: 53
Thanks Siddharth,

It worked, but as you told I will try to see which way I can update,bcoz I have to update listbox (I mean if the user wishes to update an item in the listbox ) I should be able to do so that it updates in DB also.

But one thing I was not able to understand is I could not see any Binding command in ur code,So how are you binding it to the Database column??

thanks again...
Feb 17 '09 #28

P: 59
Buddy, I have posted three other posts too, Please refer to them for binding and all.
Feb 17 '09 #29

P: 59
This line of code binds the data:-
Expand|Select|Wrap|Line Numbers
  1. listBox1.DataSource = ds.Tables["Category"]; 
Every bindable control has the property DataSource. It mentions the source of the data to which you can bind the control.
You may choose to bind the control to a data table, Data Column, Array of objects etc.

Regards,
Siddhartha
Feb 17 '09 #30

P: 53
Thanks a lot Siddhart, Your answers are really helping me a lot.....
Feb 18 '09 #31

P: 53
Hello Siddharth,

I accidently deleted my database , So i created a database again and created my table again and also wrote new storedprocedure which is used to store the textbox items in the Database column categoryname.

here is the method:

void SavetoDB()
{
SqlDataAdapter categoryDataAdapter = new SqlDataAdapter(new SqlCommand("SELECT categoryname,datecreated FROM Category", connection));

categoryDataAdapter.InsertCommand = new SqlCommand("databaseinsert", connection);
SqlCommand cmdInsert = categoryDataAdapter.InsertCommand;
cmdInsert.CommandType = CommandType.StoredProcedure;
cmdInsert.Parameters.Add(new SqlParameter("@categoryname", SqlDbType.VarChar,50,"categoryname"));
cmdInsert.Parameters.Add(new SqlParameter("@datecreated", SqlDbType.VarChar,50,"datecreated"));
categoryDataAdapter.FillSchema(cDS, SchemaType.Source);
DataTable pTable = cDS.Tables["Table"];
//pTable.TableName = "Category";

// Inserting the data from the textbox into dataset

DataRow cOrderRow = cDS.Tables["Category"].NewRow();
cOrderRow["categoryname"] = textBox1.Text;
cOrderRow["datecreated"] = DateTime.Now;
cDS.Tables["Category"].Rows.Add(cOrderRow);

// Updating the Dataset
categoryDataAdapter.Update(cDS, "Category");

} //end of funtion savetoDB

But now when i run the program ,and after entering item in the textbox it says sotred procedure not found and the execution stops at categoryDataAdapter.Update(cDS, "Category"); //

Earlier it was working fine before me deleting the DB, now I have created exacly like i did before,but still giving this error.Help....please
Feb 18 '09 #32

P: 53
Hello Siddharth,

Ignore the previous question, I got it right (about the error), but still my database takes only one character , i checked the length of the categoryname in properties, it is set to 1, that is the reason why its taking only one character (as you had told) ,but how do I change it?? its not allowing me to change....

Thanks a lot......
Feb 19 '09 #33

P: 59
Try this on the Query Analyser of the SQL DB.

Expand|Select|Wrap|Line Numbers
  1. ALTER TABLE Category
  2. ALTER COLUMN CategoryName varchar(80)
Which version of MS SQL are you using ?
Feb 19 '09 #34

P: 53
Hello Siddharth,

Have few more doubts,

Intially I have a textbox1 when i write item to the textbox and click save button it goes to database category column and saves in the db.

here is my code:
void SavetoDB()
{

SqlDataAdapter categoryDataAdapter = new SqlDataAdapter(new SqlCommand("SELECT categoryname,datecreated FROM Category", connection));

categoryDataAdapter.InsertCommand = new SqlCommand("databaseinsert", connection);
SqlCommand cmdInsert = categoryDataAdapter.InsertCommand;
cmdInsert.CommandType = CommandType.StoredProcedure;
cmdInsert.Parameters.Add(new SqlParameter("@categoryname", SqlDbType.VarChar,50,"categoryname"));
cmdInsert.Parameters.Add(new SqlParameter("@datecreated", SqlDbType.VarChar,50,"datecreated"));
categoryDataAdapter.FillSchema(cDS, SchemaType.Source);
DataTable pTable = cDS.Tables["Table"];


// Inserting the data from the textbox into dataset

DataRow cOrderRow = cDS.Tables["Category"].NewRow();
cOrderRow["categoryname"] = textBox1.Text;
cOrderRow["datecreated"] = DateTime.Now;
cDS.Tables["Category"].Rows.Add(cOrderRow);

// Updating the Dataset
categoryDataAdapter.Update(cDS, "Category");

} //end of funtion savetoDB
The above function is working fine.......

next I have to populate the listbox with the with the items in the DB category column
so I have a method called popoulatelistbox
here is the code :
void populatelistbox()
{




SqlDataAdapter da = new SqlDataAdapter("Select * from category", connection);
listBox1.Items.Clear();
try
{
cDS.Clear();
da.Fill(cDS, "Category");

listBox1.DataSource = cDS.Tables["Category"];
listBox1.DisplayMember = "categoryname";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}



} //end of populate listbox method

This is also working fine.....................

Now if I have to change an item in the listbox after it populates ,the user should be able to do
this i am taking care in doubleclick even of the save button
here is the code:

private void listBox1_DoubleClick(object sender, System.EventArgs e)
{


if (listBox1.SelectedItems.Count != 0)
{
globalindex = listBox1.SelectedIndices[0];
textBox1.Text = cDS.Tables["Category"].Rows[globalindex]["categoryname"].ToString();
textBox1.SelectAll();
}


}

Here is the problem:

suppose the llistbox has item Electricity and if the user wishes to change it as energy, If I double click on electricity and when Electricity appears in the textbox and If i change it to Energy,its not updating Electricity, instead its writing Energy as an new item in the Listbox as well as Database table.

How do correct this????

Thanks a lot Siddharth..........
Feb 19 '09 #35

P: 59
hehehe.....
Its simple....because your user is clicking the same button as "Adding" to save the change he made.
On clicking the "Add" button the method "SaveToDB()" is being called. Isn't that simple to understand.
How can the method "SaveToDB()" update the value..it adds the value and hence the error. Am I right? You need to provide another button for edit or you need to handle the click of the "Save" button in two different ways. For editing and for adding.
By the way did the Database Column problem got solved with the code i provided yesterday?

Regards,
Siddhartha
Feb 20 '09 #36

P: 59
Just a request. Try to keep your posts a bit more properly formatted.
You can include the code inside the [code] tag "
Expand|Select|Wrap|Line Numbers
  1.  //PUT CODE HERE 
"

Regards,
Siddhartha
Feb 20 '09 #37

P: 53
I will try that double clicking the item in the listbox and editing it later......

I was trying to bind my combobox in my datagridview to my categoryname column in my Category table. This is how I tried,not working :(

Expand|Select|Wrap|Line Numbers
  1. void bindcombobox()
  2.         {
  3.             SqlDataAdapter da = new SqlDataAdapter("Select * from category", connection);
  4.    cDS.Clear();
  5.    da.Fill(cDS, "Category");
  6.    DataGridViewComboBoxColumn combocolumn = new     DataGridViewComboBoxColumn();
  7.  
  8.             combocolumn.DataSource = cDS.Tables["Category"];
  9.             combocolumn.DisplayMember = "categoryname";
  10.            combocolumn.ValueMember = "categoryname";*/
  11. }
  12.  
  13.  
I dont know where I am going wrong...

And regarding that DB length thing....I was able to change the Length property of categoryname, but still the same, I had same problem with datecreated column and I changed datecreated length (as per ur suggestion) and now datecreated is working fine,but I dont know whats wrong with this categorname,but will try to figureout...


Thanks a lot....
take care...
Feb 20 '09 #38

P: 59
Check out this link.
Feb 20 '09 #39

P: 53
hello Siddharth,
I tried the link which you had sent,but still not working, is there any other resource,

I have a combobox column in my datagridview, in my combobox I should be able to display all the items in the categoryname column of the Category column. if the categoryname has food,electricity the combobox column should be able to give pulldown which has food ,electricity so that the user can select one.

Thanks a lot..
Feb 20 '09 #40

P: 53
Hello Siddharth,

Even my updating the category table when the user double clicks in the listbox is also not working.

This is how I am trying......

Expand|Select|Wrap|Line Numbers
  1. void SavetoDB()
  2.         {
  3.            //Inserting the data from the textbox into dataset
  4.  
  5.             DataTable pTable = cDS.Tables["Table"];
  6.             DataRow cOrderRow = cDS.Tables["Category"].NewRow();
  7.             cOrderRow["categoryname"] = textBox1.Text;
  8.             cOrderRow["datecreated"] = DateTime.Now;
  9.             cDS.Tables["Category"].Rows.Add(cOrderRow);
  10.  
  11.             if (textBox1.Text != String.Empty && globalindex == -1)
  12.             {
  13.  
  14.                 SqlDataAdapter categoryDataAdapter = new SqlDataAdapter(new SqlCommand("SELECT categoryname,datecreated FROM Category", connection));
  15.  
  16.                 categoryDataAdapter.InsertCommand = new SqlCommand("databaseinsert", connection);
  17.                 SqlCommand cmdInsert = categoryDataAdapter.InsertCommand;
  18.                 cmdInsert.CommandType = CommandType.StoredProcedure;
  19.                 cmdInsert.Parameters.Add(new SqlParameter("@categoryname", SqlDbType.VarChar, 50, "categoryname"));
  20.                 cmdInsert.Parameters.Add(new SqlParameter ("@datecreated", SqlDbType.VarChar, 50, "datecreated"));
  21.                 categoryDataAdapter.FillSchema(cDS, SchemaType.Source);
  22.  
  23.  
  24.  
  25.  
  26.  
  27.                 // Updating the Dataset
  28.                 categoryDataAdapter.Update(cDS, "Category");
  29.  
  30.  
  31.             }
  32.  
  33.             else if (globalindex != -1)
  34.             {
  35.  
  36.                 SqlDataAdapter categoryDataAdapter = new SqlDataAdapter(new SqlCommand("SELECT categoryname,datecreated FROM Category", connection));
  37.  
  38.                 categoryDataAdapter.UpdateCommand = new SqlCommand("databaseupdate", connection);
  39.                 SqlCommand cmdupdate = categoryDataAdapter.UpdateCommand;
  40.                 cmdupdate.CommandType = CommandType.StoredProcedure;
  41.                 cmdupdate.Parameters.Add(new SqlParameter("@categoryid", SqlDbType.Int, 12));
  42.                 cmdupdate.Parameters.Add(new SqlParameter("@categoryname", SqlDbType.VarChar, 50));
  43.  
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.                 //categoryDataAdapter.FillSchema(cDS, SchemaType.Source);
  51.                // DataTable pTable = cDS.Tables["Table"];
  52.  
  53.  
  54.                 // Inserting the data from the textbox into dataset
  55.                 Object []array = new Object[2];
  56.  
  57.  
  58.  
  59.                 array[1] = textBox1.Text;
  60.                 array[0] = listBox1.SelectedIndex;
  61.  
  62.  
  63.  
  64.                 /*DataRow cOrderRow1 =*/
  65.                 cDS.Tables["Category"].LoadDataRow(array,LoadOption.OverwriteChanges);
  66.  
  67.                // cOrderRow["categoryname"] = textBox1.Text;
  68.                 //cOrderRow["categoryid"] = listBox1.SelectedIndex;
  69.                 //cDS.Tables["Category"].Rows.Add(cOrderRow);
  70.  
  71.                 // Updating the Dataset
  72.                 //categoryDataAdapter.Update(cDS, "Category"); //calls stored proc
  73.  
  74.             }
  75.  
  76.         } //end of funtion savetoDB
  77.  
  78.  
  79.  
Here is my stored Procedure:

create procedure databaseupdate (@index int ,@newcategoryname nvarchar)
as update Category
set categoryname = @newcategoryname
where categoryid = @index;

when the user double click in the listbox and tries to alter i am checking if the globalindex !=1, then the old categoryname has to be replaced with the new category name in the listbox as well as in my categoryname column of the Categorytable.

Siddharth, I am really new to this Object Oreiented concepts and .NET,so all together I am lost...

Please guide me on this...

Thanks a lot...
Feb 22 '09 #41

P: 53
Hello Siddharth,

I would like also to tell u my Category table columns

1. categoryid which incriments automatically as I save something to DB
2. categorname, which takes value form textbox1.txt
3. datecreated which takes value form DataTime.Now

Thaks a lot
Feb 22 '09 #42

P: 59
Hi,
Reseting the globalIndex back to -1 after you have finished updating, should be done. Do that and check.
The second condition should be:

Expand|Select|Wrap|Line Numbers
  1. else if (textBox1.Text != String.Empty && globalindex != -1)
You would not want a category to be edited to a blank text. Would you?

Why don't you declare the categoryDataAdapter at a global level and define the
update, delete and insert command once and for all in the Form1 constructor.
Why to declare dataAdapters again and again as you update, delete or insert records? To summarize, things to be done are:
1) Declare the dataAdapter object at the class level.
2) Define the Update, Insert, Delete commands of the Adapter in the form Constructor or form load event.
3) Reset the global Index after you edit/delete a record.

Regards,
Siddhartha
Feb 23 '09 #43

P: 53
Hello Siddharth,

Here is the code to update the listbox and categoryname in Category table.

Expand|Select|Wrap|Line Numbers
  1.  
  2.  else if (textBox1.Text != String.Empty && globalindex != -1)
  3.             {
  4.              SqlCommand cmdupdate = new SqlCommand("databaseupdate",connection); 
  5. cmdupdate.CommandType = 
  6. CommandType.StoredProcedure; 
  7. cmdupdate.Parameters.Add(
  8. new SqlParameter("@categoryid", SqlDbType.Int, 12));
  9. cmdupdate.Parameters.Add(new SqlParameter("@categoryname", SqlDbType.VarChar, 50)); 
  10.  
  11. // when I say @categoryid and @categoryname, should I tell the column name
  12.  //of the DB table, I am not sure how this SQLParameter class works
  13.  
  14. Object []array = new Object[2]; 
  15. array[1] = textBox1.Text;
  16. array[0] = listBox1.SelectedIndex;
  17. //Start DataBase Update 
  18. cmdupdate.Parameters[0].Value=array[0];
  19. cmdupdate.Parameters[1].Value=array[1];
  20. int i=cmdupdate.ExecuteNonQuery(); 
  21. /*(Here its giving me an error saying that "Procedure  function 'databaseupdate' expects parameter '@globalindex', which was not supplied.) */
  22. //End Of database Update 
  23.  
  24. cDS.Tables[
  25. "Category"].LoadDataRow(array,LoadOption.OverwriteChanges);//(I am not sure how it works)
  26.  
  27.                 cDS.AcceptChanges();
  28.  
  29.  
Here is my procedure:

create procedure databaseupdate (@categoryid int,@newcategoryname nvarchar)
as update Category
set categoryname = @newcategoryname
where categoryid = @categoryid;

Thanks a lot Siddharth
Feb 23 '09 #44

P: 59
For showing the data in a datagridView Combo box try the following code in the page load event method:

Expand|Select|Wrap|Line Numbers
  1. SqlDataAdapter da = new SqlDataAdapter ("Select * from category",finConnection);            
  2.             listBox1.Items.Clear();
  3.             try
  4.             {
  5.                 ds.Clear();
  6.                 da.Fill(ds, "Category");
  7.                 //listBox1.DataSource = ds.Tables["Category"];
  8.                 //listBox1.DisplayMember = "CategoryName";  
  9.                 dataGridView1.DataSource = ds.Tables["Category"];
  10.                 dataGridView1.Columns.Remove("CategoryId");
  11.  
  12.                 DataGridViewComboBoxColumn listCol = new DataGridViewComboBoxColumn();
  13.                 listCol.HeaderText = "Category";
  14.                 listCol.DisplayIndex = 0;
  15.  
  16.                 listCol.DataPropertyName = "CategoryId";
  17.                 listCol.DataSource = ds.Tables["Category"];
  18.                 listCol.DisplayMember = "CategoryName";
  19.                 listCol.ValueMember = "CategoryId";
  20.                 dataGridView1.Columns.Add(listCol);
  21.             }
  22.             catch (Exception ex)
  23.             {
  24.                 MessageBox.Show(ex.Message);
  25.             }
I have tried the code at my side, its working fine, so don't tell me this is not working. The code was clearly present in the link provided by me earlier. Please check for the column names as they may be different at your side. The text in the code that is within quotes are column names.

Regards,
Siddhartha
Feb 24 '09 #45

P: 59
Btw, when are you showing the data in the datagridview and when are you showing it in list box?
I smell some ambiguity in your approach, how are tyou displaying the data?
Feb 24 '09 #46

P: 53
Hi Siddharth,

your code worked fine....Thanks a ton........
One more question is, once the user selects the item from the combox then it should be transfered to another table called Transact table.
Can you give me hint on how to acheive this. I know I am asking u a lot,but thats how I am able to learn,otherwise I feel I am lost...

Now I have a datagridview which has columns
1.categoryname(combobox column) which gets data from categoryname column of Category table

2. Amount (textbox)

3. Description(text box).

The above is acheived by following code:(given by u slighlty changed)

Expand|Select|Wrap|Line Numbers
  1.  
  2. SqlDataAdapter da = new SqlDataAdapter("select * from Category", connection);
  3.                      try
  4.            {
  5.                cDS.Clear();
  6.                da.Fill(cDS, "Category");
  7.  
  8.                DataGridViewComboBoxColumn listCol = new DataGridViewComboBoxColumn();
  9.                DataGridViewTextBoxColumn text = new DataGridViewTextBoxColumn();
  10.                DataGridViewTextBoxColumn amount = new DataGridViewTextBoxColumn();
  11.  
  12.  
  13.                listCol.HeaderText = "categoryname";
  14.                listCol.DisplayIndex = 0;
  15.                text.HeaderText = "description";
  16.                text.DisplayIndex = 1;
  17.                amount.HeaderText = "amount";
  18.                amount.DisplayIndex = 2;
  19.  
  20.  
  21.                listCol.DataPropertyName = "categoryid";
  22.                listCol.DataSource = cDS.Tables["Category"];
  23.                listCol.DisplayMember = "categoryname";
  24.                listCol.ValueMember = "categoryid";
  25.                dataGridView1.Columns.Add(listCol);
  26.                dataGridView1.Columns.Add(text);
  27.                dataGridView1.Columns.Add(amount);
  28.  
  29.  
  30.  
  31.  
  32.            }
  33.            catch (Exception ex)
  34.            {
  35.                MessageBox.Show(ex.Message);
  36.            } 
  37.  
  38.  
  39.  
Design of my Datagridview

Categoryname(combocolulmn) Description Amount
Electricity(pulled from CombC) House 30.00

Now I want all these in a Transaction table in my DB

This is How I am trying:

Expand|Select|Wrap|Line Numbers
  1.  
  2.  private void apply_Click(object sender, EventArgs e)
  3.       {
  4.  
  5.  
  6.           SqlDataAdapter categoryDataAdapter = new SqlDataAdapter(new SqlCommand("SELECT * FROM Transact_table", connection));
  7.  
  8.           categoryDataAdapter.InsertCommand = new SqlCommand("databaseinserttransact", connection);
  9.           SqlCommand cmdInsert = categoryDataAdapter.InsertCommand;
  10.           cmdInsert.CommandType = CommandType.StoredProcedure;
  11.           cmdInsert.Parameters.Add(new SqlParameter("@description", SqlDbType.NVarChar, 50, "description"));
  12.           cmdInsert.Parameters.Add(new SqlParameter("@money", SqlDbType.Money, 50, "money"));
  13.           categoryDataAdapter.FillSchema(cDS, SchemaType.Source);
  14.           DataTable pTable = cDS.Tables["Table"]; //Represents one table in DataSet
  15.  
  16.  
  17.           // Inserting the data from the textbox into dataset
  18.  
  19.           DataRow cOrderRow = cDS.Tables["Transact_table"].NewRow(); 
  20.           cOrderRow["description"] = ??????????( I am struck here), dont know how to get data from amount column and moneycolumn and combocolumn
  21.          cOrderRow["money"] =;
  22.          cOrderRow["combocolumndata"] = 
  23.           cDS.Tables["Transact_table"].Rows.Add(cOrderRow);
  24.  
  25.  
  26.  
  27.  
  28.           // Updating the Dataset
  29.           categoryDataAdapter.Update(cDS, "Transact_table");*/
  30.  
  31.  
  32.  
  33.  
  34.  
  35.       }
  36.  

I tried creating object of datgridview1combocolumn, datagridview1text global
and tried to get the Textproperty ,but not working.

I know my Design sounds weird, As this is my 1st object oriented .NET project,I might be going through complex design,but thats what I can think as of now till I get hold of language properly.

Thanks a lot
Feb 24 '09 #47

P: 59
In object oriented programming (especially when dealing with UI applications) a lot is guided by the events.
Events are raised whenever user responds to the UI. For examle a button click is an event, item double click of a listbox was an event which we handled. .Net has ready made events for controls which you can handle, considering the exendibility that microsoft always provide, you can also create your events and handle them.
You need to be very precise and discrete while deciding which event to handle.
I guess you are handling the ItemIndexChanged event of the dataGridView Combo box column. I see you have handled the event in the following method
Expand|Select|Wrap|Line Numbers
  1. private void apply_Click(object sender, EventArgs e) 
  2.  
  3. }
This means, whenever the itemIndex changed event is raised this method will be called. Right?
Every event handler method (like the above one) carries two parameters "object sender" . This tells you who is the sender of this event or who is responsible for this event being raised? In case of listBox doubleclick event it was the listBox.Since you never know who a sender can be you have to keep its type the most generic i.e. an object.
The second parameter is the EventArgs e. This parameter contains every required information about the event.
If inside your method you type e and then . Visual Studio, by virtue of intellisence, will display a list of all the information that the parameter "e" can display. The solution to your problem lies in that list.
Let me know if this reply helped you.

Just a suggestion:
ComboBox selectedItemIndex changed event is an extremely wrong event to save data in. Just think it yourself, if you select a wrong item, you will end up saving the same in the database, of course you can change that, but its not worth hitting the database as it increases the cost of application, leave apart the misery that it will bring upon the user with its slowed performance.
Give a proper thought and then design the application.

All the best.
Regards,
Siddhartha
Feb 25 '09 #48

P: 53
Hello Siddharth,
Thanks for the reply....It is very helpful, I understood about the events very nicely..thanks a lot..
private void apply_Click(object sender, EventArgs e)
{

}

The above method is just a button click event(The text of the button is "apply"), I should have mentioned in my last question(sorry about that)

When i click that "apply" button I should store the gridview1 columns contents in my transaction table using storedprocedure. Since my gridview has 3 column

1.categoryname(combobox)
2.Amount(textbox)
3.Description(textbox)

categoryname selected by the user by the pull down list of the combobox, Amount and the description the user enters.

All these I have to able to store to a database table called "Transaction" using storedprocedure or any other method is also fine.

Give me some idea.....How do I proceed with this.

Thanks a lot for your help Siddharth..
take care
Feb 25 '09 #49

P: 59
Hi,

If it is like you get the combobox items (of the ComboBoxColumn) from the category table and the other contents of the gridView from the "Transaction" table, you may bind the dataGridView to the "Transaction" table and just use the "DataAdapter.Update()" method.
It will be simple to use with minimal code.
However note that you need to have a primary key in the table on which you wish to use the Update method of the Data Adapter. I don't think you have a primary key in the transation table. So define a column like Transaction_ID.
Also use the CategoryId column of the Category table in the transaction table (rather than the categoryName column) to be as the foreign key in the table transaction.

All the best.

Regards,
Siddhartha
Feb 26 '09 #50

62 Replies

Post your reply

Sign in to post your reply or Sign up for a free account.