Use can implement UserControl.
You can create more of them and you can then "loop" through them to show completely different controls in the same spot of form.
Use can implement UserControl.
You can create more of them and you can then "loop" through them to show completely different controls in the same spot of form.
finally :)
but its not a problem, if I started to help you, then I cannot just quit somewhere in the middle of a discusson, or before you dont get what you want it.
PS: you could vote up some posts ++ :)
best regards,
bye
hmm, what abou this:
private void button1_Click(object sender, EventArgs e)
{
List<int> rowIndexes = new List<int>();
foreach (int index in listBox1.SelectedIndices)
{
DataRowView view = listBox1.Items[index] as DataRowView;
int id = Convert.ToInt32(view["ID"]);
string name = view["Name"].ToString();
listBox2.Items.Add(name);
//add row index to list:
rowIndexes.Add(index);
}
for (int i = rowIndexes.Count; i > 0; i--)
table.Rows.RemoveAt(rowIndexes[i - 1]);
table.AcceptChanges();
}
Bind dgv to some dataTable (1st create dataTable, columns for it, and then bind it to datagridview). Then use SqlDataAdapter class to do insert or update command.
Ups, really sorry, I did a stupid mistake. You were right, it really did remove only one (1st) item.
Check this out now (now I really had to dig into my brains to make it work) :)
List<int> rowIndexes = new List<int>();
foreach (int index in listBox1.SelectedIndices)
{
DataRowView view = listBox1.SelectedItem as DataRowView;
int id = Convert.ToInt32(view["ID"]);
string name = view["Name"].ToString();
//add the id or name to lsitBox2 (or both as DataRow)!
rowIndexes.Add(index);
}
for (int i = rowIndexes.Count; i > 0; i--)
table.Rows.RemoveAt(rowIndexes[i - 1]);
table.AcceptChanges();
How many items to you select? More then one?
Yes, this looks fine, and it has to work.
And if you dont need the value (this is ID column) you can erase this code from the event.
Iam glad it did.
So you can close this thread by marking it as answered.
bye,ybe
Did you put all THESE code into button_Click event:
List<DataRow> rowsToRemove = new List<DataRow>(); //add this !!
for (int i = 0; i < listBox1.SelectedItems.Count; i++)
{
DataRowView view = listBox1.SelectedItem as DataRowView;
int id = Convert.ToInt32(view["course_id"]);
string name = view["Course_name"].ToString();
//add the id or name to lsitBox2 (or both as DataRow)!
listBox1.Items.Add(name); //adding name only!
//then...
//add row to list:
rowsToRemove.Add(view.Row);
}
//now remove selected rows: add this too!!
foreach (DataRow row in rowsToRemove)
table.Rows[0].Delete();
Copy paste it as it IS.
Because it works 100%. I tested it.
What are you doing, some kind of a login?
eh, thats only if you want to use the option of choosing more item as a time. By default, you can select only one item.
---------
Dont look about my dummy code. Leave it alone, its there only to run my test code.
But its the same thing; I filled dataTable.
---------
To remove selected items from listBox1 use my code from button1_Click event.
thx Ketsuekiame.
I wasnt around this morning...
I am glad it does.
bye.
Here, I did the whole you you need:
DataTable table;
public Form1()
{
InitializeComponent();
table = new DataTable("myTable");
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
//adding some example data:
for (int i = 0; i < 6; i++)
table.Rows.Add(i, "name " + i);
listBox1.DataSource = table.DefaultView;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "ID";
listBox1.SelectionMode = SelectionMode.MultiSimple;
}
private void button2_Click(object sender, EventArgs e)
{
List<DataRow> rowsToRemove = new List<DataRow>();
for (int i = 0; i < listBox1.SelectedItems.Count; i++)
{
DataRowView view = listBox1.SelectedItem as DataRowView;
int id = Convert.ToInt32(view["ID"]);
string name = view["Name"].ToString();
//add the id or name to lsitBox2 (or both as DataRow)!
//then...
//add row to list:
rowsToRemove.Add(view.Row);
}
//now remove selected rows:
foreach (DataRow row in rowsToRemove)
table.Rows[0].Delete();
}
I almost forgot how to delete rows from listBox - when these are databound!!!
So vote some ++; :)
bye
Sure, you cannot midify the number of item in a collection.
What can we do?
hmmm, let me see...
I think I know...
Do it this way:
private void button1_Click(object sender, EventArgs e)
{
DateTime date = DateTime.MinValue;
if (!DateTime.TryParse(textBox1.Text, out date))
{
string[] strSplit = textBox1.Text.Split('/');
if (strSplit.Length == 1)
date = new DateTime(int.Parse(strSplit[0]), 1, 1);
else if (strSplit.Length == 2)
date = new DateTime(int.Parse(strSplit[0]), int.Parse(strSplit[1]), 1);
}
MessageBox.Show("Real date time is " + date);
}
Now you use "date" variable where ever you need to, or to set dateTimePicker control (to set date), or what ever.
Hope it helps,
bye
Did you bind the listBox1, using DataSource property from DataTable?
If so, you have to 1st get the item and value from listBox item and add it some other place (in your case to listBox2):
for(int i = 0; i < listBox1.SelectedItems.Count; i++)
{
DataRowView view = listBox1.SelectedItem as DataRowView;
string item = view["ColumnNameOfItem"].ToString(); //can be some name
int value = Convert.ToInt32(view["ColumnNameOfValue"]); //can be some id (number)
listBox2.Items.Add(item); // it you want to add item (you can add value as well);
}
ColumnNameOfItem (or OfValue) are the names of fields in your dataTable (and same are in dataBase as well). Insteads of names you can use indexes (0 and 1, but without quotation marks).
Hope it helps.
bye
pop operation? What is that?
int array cannot be empty. Empty is for string. Int can have only numbers. So when you initialize a new integer array all indexes set to zero This is 0 and not empty.
If no parameters to pass:
//1. way:
new Thread(new ThreadStart(MethodNoParams)).Start();//calling new method
//2. longer way (if you need a "t" variable maybe):
Thread t = new Thread(new ThreadStart(MethodNoParams)); //calling new method
t.Start();
If parameters to pass:
object obj ="some param";
Thread t1 = new Thread(new ParameterizedThreadStart(MethodWithParams)); //calling new method
t1.Start(obj);
MethodNoParams is a method that accepts no parameters, while MethodWithParams is a method which accpets parameter.
Just for your knowledge:
private void MethodNoParams()
{
}
private void MethodWithParams(object args)
{
}
YOu have to ge the correct connection string.
One last questions:
1. Is this Sql Server 2008 Express edition?
2. Is Db located on your hdd (hard drive) at the moment?
You can adda rep +1 :)
I was trying really hard on the Sunday afternoon.
One thing to mention before even starting looking into this "mess" of the code.
Use parameterized query. Check URL="http://blog.divergencehosting.com/2009/04/09/using-parameters-parameterized-queries-database-interactions-cshar-vbnet/"][/UhereRL] what this means.
It basicly means that you dont specify textBoxes values directly in the query, but you add them in the command.
Next, it would be better to get all the data from DB into a dataTable, and then use dataBinding for each textBox. Check here what dataBinding is.
Take your time. Its not so easy task to do, especially if you didnt do it before.
If you have any issues with C# code there, use C# to VB converter.
Hope it helps,
bye
I dont know how you will validate your arabic datetime (Iam not familiar with it), so this is up to you. Iam sure you can do something.
But most impoertant thing is that you put all the code into TextChanged event of textBox control.
Ok, I did an example code, how to upload files and show then in the list (listBox control). Then I added a richTextBox control on the form which is meant to show the file`s content (text usually).
NOTE: Dont forget to add a new namespace on top of the class when using FileInfo and StreamReader classes. This namespace its called System.IO;
So here it is:
//add a namespace on top here:
using System.IO;
//among other namespases...
public partial class Form1 : Form
{
List<FileInfo> listFiles;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "text files (*.txt)|*.txt|xml files (*.xml)|*.xml";
open.Multiselect = true;
open.InitialDirectory = @"C:\";
if (open.ShowDialog() == DialogResult.OK)
{
listFiles = new List<FileInfo>();
FileInfo fi;
for (int i = 0; i < open.FileNames.Length; i++)
{
fi = new FileInfo(open.FileNames[i]);
listFiles.Add(fi);
listBox1.Items.Add(Path.GetFileName(fi.FullName));
}
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex > -1)
{
richTextBox1.Text = "";
string fileName = listBox1.SelectedItems[0].ToString();
foreach (FileInfo fi in listFiles)
{
if (fileName == Path.GetFileName(fi.FullName))
{
using (StreamReader sr = new StreamReader(fi.FullName))
{
string text;
while ((text = sr.ReadLine()) != null)
richTextBox1.AppendText(text + "\n");
}
}
}
}
}
}
This code works, and so far it only opends *.txt files.
BTW, what are the invalid characters?
But TextChaged event does. Use this one, and do restrictions inside this event.
There is no problem with showing the files (list of files), the problem is when you want to show file`s content. There is a big difference if file is xml, txt or some oteher type.
So what can it be?
A win form?
Now it makes more sence why its not working. You didnt says your DB is Express edition.
If so, you must include "SQLExpress" keyword in the conn.string.
Check these two out:
Connecting to a Local SQL Server Express Instance:
"Server=.\SQLExpress; AttachDbFilename=yourMDFFile.mdf; Database=yourDB; Trusted_Connection=Yes;"
Connecting to a Local SQL Server Express Instance (Database File in Data Directory):
"Server=.\SQLExpress; AttachDbFilename=|DataDirectory|yourMDFFile.mdf; Database=yourDB;
Trusted_Connection=Yes;"
So this means 2 things:
- or you dont retreive the right data
- or you dont have the correctly.
Can we see some of your code that does these two things?
You need a connection string appropriate for Microsoft SQL 2008 R2 database.
Go here to find your connection string.
Btw, is your DB Express or not?
This only depends of the structure of your code - where to catch exceptions. But ordinary we catch then on the place where they might occure.
You are welcome mate.
best regards,
bye
Where did you find this connection string anyway?
Try this conn.string:
"Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;"
And go here to check for the right connection string, if the one I pasted will not work.
--------------
One more thing to mention:
Go to SQL Server Management Studio,
Right click on the database,
select properties,
select Security,
Click ON> SQL Server and Windows Authentication mode ON.
Then an explicit username connection will work.
Hi Mitja,
as I said I update the program.cs to
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace FinalFormLoader { //Program.cs file: static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1());// open Form1 } } //form1: public partial class Form1 : Form { public Form1() { InitializeComponent(); new Form2().Show(); //open Form2 } } }
So this whole code is in your program.cs file?? Your code now has two implementations of Form1.
If so, delete what is of form1.
Form1 has its own class and its own code.
Maybe you have to write the full path to the database:
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\Folder1\Folder2\LocalAccess40.mdb"
I did an example code for you only, so you can see how this should be done:
Private dgv As DataGridView
Private tableMain As DataTable
Public Sub New()
InitializeComponent()
'creating and adding columns to dgv:
dgv = New DataGridView()
dgv.Width = 470
Me.Controls.Add(dgv)
'get data from DB:
tableMain = GetDataFromDB()
'creating two more column to dataTable:
tableMain.Columns.AddRange(New DataColumn() {New DataColumn("column 3", GetType(String)), New DataColumn("column 4", GetType(String))})
'bind table to dgv:
dgv.DataSource = tableMain.DefaultView
End Sub
Private Function GetDataFromDB() As DataTable
Dim table As New DataTable()
'get data from database...
'I will only create two columns and add some example rows..
table.Columns.AddRange(New DataColumn() {New DataColumn("column 1", GetType(Integer)), New DataColumn("column 2", GetType(String))})
For i As Integer = 1 To 5
table.Rows.Add(i, "item " & i)
Next
Return table
End Function
Private Sub button1_Click(sender As Object, e As EventArgs)
'mow lets insert data to DB:
Dim bOk As Boolean = True
Using sqlConn As New SqlConnection("connString")
Dim cmd As SqlCommand = Nothing
For Each row As DataRow In tableMain.Rows
cmd = New SqlCommand()
cmd.CommandText = "INSERT INTO MyTable VALUES (@param1, @param2, @param3, @param4)"
cmd.Parameters.Add("@param1", SqlDbType.Int).Value = Convert.ToInt32(row(0))
cmd.Parameters.Add("@param2", SqlDbType.VarChar, 50).Value = row(1).ToString()
cmd.Parameters.Add("@param3", SqlDbType.VarChar, 50).Value = row(2).ToString()
cmd.Parameters.Add("@param4", SqlDbType.VarChar, 50).Value = row(3).ToString()
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message)
bOk = False
Exit Try
End Try
Next
End Using
If bOk Then
MessageBox.Show("All data inserted succesfully.")
End If
End Sub
Hopeit helps.
As charlybones said, there is 100% a problem in the connection string structure.
Remove Integrated Security=True from your connection string and (optional) add Persist Security Info=True;
From MSDN:
Integrated Security - When false, User ID and Password are specified in the connection. When true, the current Windows account credentials are used for authentication.
This is not the whole code you have. There has to be another one for creating and initializing (or opening) Form1. Thats why you get this error message.
If your DGV is data bound (so the DGV`s property DataSource is used), then all the changes made in the DGV will automatically reflect in the dataTable (or dataSet) as well.
Then if you want to do updates in the database as well, you have to use Update SqlCommand.
Take a lookt at this example of mine I did a copule of months ago
public void DAL_UpdateStudentsTable(DataTable table)
{
using (SqlConnection sqlConn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = @"UPDATE Students SET " +
"StudentID = @id, " +
"FirstName = @first, " +
"LastName = @last, " +
"Birthday = @birthday, " +
"PersonalNo = @personal " +
"WHERE StudentID = @oldId";
cmd.Parameters.Add("@id", SqlDbType.Int, 5, "StudentID");
cmd.Parameters.Add("@first", SqlDbType.VarChar, 50, "FirstName");
cmd.Parameters.Add("@last", SqlDbType.VarChar, 50, "LastName");
cmd.Parameters.Add("@birthday", SqlDbType.DateTime, 1, "Birthday");
cmd.Parameters.Add("@personal", SqlDbType.VarChar, 50, "PersonalNo");
SqlParameter param = cmd.Parameters.Add("@oldId", SqlDbType.Int, 5, "StudentID");
param.SourceVersion = DataRowVersion.Original;
cmd.Connection = sqlConn;
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.UpdateCommand = cmd;
da.Update(table);
}
}
}
}
As you can see, I pass a DataTable to the method which has a code to do an UPDATE. Using SqlDataAdaper will execute the changes.
If you only want to add a Exception then do it like:
public int Sum(int a, int b)
{
if ((a < 0) || (b < 0))
{
throw new ArgumentException("Number cannot be negative");
}
else
{
return a + b;
}
}
Sure it does. I tried it.
Take a look at this picture, its a leaving prove:
http://file.si/files/46441_rioid/C%23_ResizeArray.jpg
Picture was taken after the code returned from the method which resized it. As you can see there are 8 indexes in the array. So this means resizing.
I did a simple example (in a few minutes) to show you how can be done:
Private dgv As DataGridView
Public Sub New()
InitializeComponent()
'creating and adding columns to dgv:
dgv = New DataGridView()
Me.Controls.Add(dgv)
Dim combo As New DataGridViewComboBoxColumn()
If True Then
combo.Name = "c2"
combo.HeaderText = "column 2"
End If
dgv.Columns.Add("c1", "column 1")
dgv.Columns.Insert(1, combo)
'adding some example rows:
For i As Integer = 1 To 4
dgv.Rows.Add(i, Nothing)
Next
' adding data into 1st column, int 2nd (combo) nothing
' and based on this column, will we now add data to comboboxcell:
For Each row As DataGridViewRow In dgv.Rows
Dim cell As New DataGridViewComboBoxCell()
Dim dataToUse As Integer = Convert.ToInt32(row.Cells(0).Value)
cell.DataSource = SetComboBoxCell(dataToUse)
dgv(1, row.Index) = cell
Next
End Sub
Private Function SetComboBoxCell(i As Integer) As List(Of String)
Dim list As New List(Of String)()
Select Case i
Case 1
list.AddRange(New String() {"A1", "B1", "C1"})
Exit Select
Case 2
list.AddRange(New String() {"A2", "B2", "C2"})
Exit Select
Case 3
list.AddRange(New String() {"A3", "B3", "C3"})
Exit Select
Case 4
list.AddRange(New String() {"A4", "B4", "C4"})
Exit Select
End Select
Return list
End Function
Convert again
Hi every one! I would like to know if it's possible to have differents items in a combo box in each row. It there is way. Please help!!! Thanks
Hi, you will have to do a loop through all the rows of datagrid and based on othe column set the comboboxcell for each cell.
UPS, so sorry.. I guess Im already asleeping here.
I forgot a return keyword:
static void Main()
{
int[] myArray = new int[4];
myArray = setLength(myArray, 8);
}
static int[] setLength(int[] myArray, int length)
{
Array.Resize(ref myArray, length);
return myArray;
}
This will do the trick mate.
good night.
You can always use try-catch blocks to catch the exception. But in this cases of yours it seems not to need one.
If your method has a return type, you have to return this type in any place in the Sum method. Otherwise the compiler will throw an error.
You can do it:
private void YourMethod()
{
int a = -2;
int b = 3;
int c = Sum(a, b);
if (c > 0)
{
//Ok!!
}
else
{
//show a message if needed
//that some of values are negative
}
}
public int Sum(int a, int b)
{
if (a < 0 || b < 0)
{
return 0;
}
else
{
return a + b;
}
}
You can subscribe to a KeyPress event of textbox control, and use this code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\b')
e.Handled = !System.Uri.IsHexDigit(e.KeyChar);
}
Or TextChanged event:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string item = textBox1.Text;
int n = 0;
if (!int.TryParse(item, System.Globalization.NumberStyles.HexNumber, System.Globalization.NumberFormatInfo.CurrentInfo, out n) &&
item != String.Empty)
{
textBox1.Text = item.Remove(item.Length - 1, 1);
textBox1.SelectionStart = textBox1.Text.Length;
}
}
You didnt set the return type to the setLenght method. You have to change the code to:
static void Main()
{
int[] myArray = new int[4];
myArray = setLength(myArray, 8);
}
static int[] setLength(int[] myArray, int length)
{
Array.Resize(ref myArray, length);
return myArray;
}
or you can use ref keyword, to return, but I would suggest you to use upper example:
static void Main()
{
int[] myArray = new int[4];
setLength(ref myArray, 8);
}
static void setLength(ref int[] myArray, int length)
{
Array.Resize(ref myArray, length);
}