This way:
" WHERE Emp_ID= '",rec.Emp_ID, "'"), clsData.con);
One more thing, you can write pluses "+" instead of commas ",", like:
" WHERE Emp_ID= '" + rec.Emp_ID + "'"), clsData.con);
This way:
" WHERE Emp_ID= '",rec.Emp_ID, "'"), clsData.con);
One more thing, you can write pluses "+" instead of commas ",", like:
" WHERE Emp_ID= '" + rec.Emp_ID + "'"), clsData.con);
Code code it self has to be ok (the strucure I mean) but I dont know about your column names and the conitional clause (where).
Where did you get the where clause and check if it really exist in the database`s table.
Sure you can update a NULL value in a particular cell. Null only refers there is no data yet in the cell (at least it worked for me), maybe it differs form database to databsse, not sure about it.
If its still doesnt work, try with Insert command.
But insert only that field.
Thx for Voting :(
I will still help you out... what you have to do is to use WHERE clause to specify for which row you want to update the datetime. Do you have any Id, or some other unique column, so you can use the comparison?
Your query them will look:
da.UpdateCommand = new SqlCommand("UPDATE WaynokaLogger SET Date = @Date WHERE YourUniqueColumn = @uniqueColumn", cs);
da.UpdateCommand.Parameters.Add("@Date", SqlDbType.Date).Value = dt;
da.UpdateCommand.Parameters.Add("@uniqueColumn", SqlDbType.Int).Value = SomeUniqueValue;
da.UpdateCommand.ExecuteNonQuery();
private void insertDate()
{
da.UpdateCommand = new SqlCommand("UPDATE WaynokaLogger SET Date = @Date", cs);
da.UpdateCommand.Parameters.Add("@Date", SqlDbType.Date).Value = dt;
da.UpdateCommand.ExecuteNonQuery();
Change this line of code (sql query) into:
OleDbCommand cmd = new OleDbCommand(Stirng.Format("INSERT INTO CHILDREN2 (Emp_ID , Child_Name, Age) VALUES ({0}, {1}, {2})", Convert.ToInt32(CaptionText.Text),txtName.Text, txtAge), clsData.con);
Do you have a WHERE clause too? I removed it from your query, becasue it didnt belonge on that place where you put it.
If you will use a Where clause then create an sql query this was:
"INSERT INTO TableName (Field1, Field2) VALUES (@paramField1, @paramField2) WHERE Field3 = @paramField3"
where params are parameters passed to the fields, and WHERE is a conditional clause, and has to be stated on the end (after specifying parameters).
You didnt tell what will be the validation like? I mean, what will you validate?!
For TextBoxes, you can do (if you have them that many) some additional method for validating textBoxes one by one.
Hi!
I want to create my own list of keywords so that if I write spells of any keyword wrong, it get's underlined like in usual compilers. How can I create a list and create an underline command?
Will you use RichTextBox control?
An ObjectListView will do exactly that and much more. It is a wrapper around a normal .NET ListView. It is open source.
Its website has a Getting Started to help you begin, as well as a whole page devoted to cell editing.
Otherwise I would stringly suggest you to use othe control, DataGridView, which is meant for this job. ListVIew is meant only for showing data, not for editing.
There is many methods to do the checking, one (and most common) is to use TryParse method:
int myNumber = 0;
if(int.TryParse(textBox1.Text, out myNumber))
{
//this is a number,
}
else
{
MessageBox.Show("Sorry, string is not a number.");
textBox1.Text = string.Empty;
}
To read a file and to get word by word (seperated one from another), then you can doit this way:
List<string> list = new List<T>();
using(StreamReader sr = new StreamReader("filePath"))
{
string line;
while((line = sr.ReadLine()) != null)
{
string[] words 0 line.Split(' ');
foreach(string word in words)
list.Add(word);
}
}
Now you have all the words in the leneric list<T>.
If you want to "combine" them, you can do it this way:
textBox1.Text = String.Join(" ", list.ToArray());
Ups, sorry, there was a typo. Check the code ones again (I changes the 1st for loop - there was a "j" instead of an "i" inside).
Check this code:
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//get columns:
for (int i = 0; i <= this.dataGridView1.ColumnCount - 1; i++)
{
string colName = dataGridView1.Columns[i].HeaderText;
xlWorkSheet.Cells[1, i] = colName;
}
//get data:
//you can erase this if you dont need data from rows:
for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
{
for (int j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
DataGridViewCell cell = dataGridView1[j, i];
xlWorkSheet.Cells[i + 2, j + 1] = cell.Value;
}
}
xlWorkBook.SaveAs(
"D:\\exp.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue,
misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue,
misValue, misValue, misValue, misValue
);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
Try this:
Console.WriteLine("The tax rate will be: {0}.", TAX_RATE) ;
Numbers in brackets are placeholders (starting from 0 on). Values that you pass are showing instead of number and bracket together.
Example:
("{0}", myValue)
We can say its a stirng format, which you can use in the same form in Win forms:
MessageBox.Show(String.Format("{0}", myValue));
Then do:
string[] LinesFile = streamReader.ReadToEnd().Split('\n');
for(int i = 0; i < LinesFile.Lenght; i++)
{
for(int j = 0; j < LinesFile[i].Lenght; j++)
{
string[] LinesData = string.Split(',');
foreach(string item in LinesData)
{
Console.WriteLine(item);
}
}
}
Console.ReadLine();
Radion button has two states. So you cannot have three option, and not if else statements (using ? : marks). Only two. So you can have:
string output;
output = "[" + this.textBoxUID.Text + "]" ;
output += this.textBoxCompany.Text;
output += this.textBoxDate.Text;
output += this.radioButtonby.Checked ? "Low" : "High"; //if is checked will be Low, ele High
this.textBoxOuput.Text = output;
And try to use Parameters, so you dont assign values directly into the query, but in query you only write parameters, which you then add bellow.
Example:
OleDbCommand com = new OleDbCommand(@"UPDATE cus SET cus_name = @param1, order = @param2 WHERE no = @param3", con);
com.Parameters.Add("@param1", OleDbType.VarChar, 50).Value = textBox4.Text;
com.Parameters.Add("@param2", OleDbType.VarChar, 50).Value = textBox6.Text;
com.Parameters.Add("@param3", OleDbType.VarChar, 50).Value = textBox7.Text;
try
{
com.ExecuteNonQuery();
}
catch(Excpeption ex)
{
//show exception if needed
}
Change the type of parameters to exact type (or varchar, or int, or... - checkl your database).
If I get your correctly, you populate DGV with some values: name, surname, and another surname - all in one cell. Now you would like to split this cell into name, and lastnames?
If Iam correct, Split it by whitespace:
Dim data As String() = dataGridView1.Rows(0).Cells(0).Value.ToString().Split(" "C)
'data array now has all name and lastname(s).
Use array data in your code.
This is anothe code I just did in a rush, what the code does, is when you click a button (even number) buttons moves, when you click it again (odd number) it stops, and so on...
My code only shows an example of the button movement down and right (at the same time).
What you have to do, is to change the directions (based on some facts and class variables). Play with the code a bit, maybe it can suit you.
Code:
Public Partial Class Form1
Inherits Form
Private thr As Thread
Private clicks As Integer
Private bStop As Boolean
Public Sub New()
InitializeComponent()
End Sub
Private Sub button1_Click(sender As Object, e As EventArgs)
If clicks Mod 2 = 0 Then
bStop = False
thr = New Thread(AddressOf Go)
thr.Start()
Else
bStop = True
thr.Join()
End If
clicks += 1
End Sub
Private Sub Go()
While (button1.Location.X + button1.Size.Width) < Me.Size.Width AndAlso Not bStop
Invoke(New moveBd(AddressOf moveButton), button1)
Thread.Sleep(50)
End While
End Sub
Private Delegate Sub moveBd(btn As Button)
Private Sub moveButton(btn As Button)
Dim x As Integer = btn.Location.X
Dim y As Integer = btn.Location.Y
btn.Location = New Point(x + 1, y + 1)
'goes 1 pixel into the right and down!!
End Sub
End Class
bye, bye
Try this code to create a moving button from one location to another:
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Namespace WindowsApplication9
Public Partial Class Form1
Inherits Form
Public Velocity As Integer() = New Integer(1) {}
Public count As Integer
Public Dest As System.Drawing.Point = New Point(394, 368), Temp As System.Drawing.Point
Public Sub New()
InitializeComponent()
End Sub
Public Function CheckV(a As Point, b As Point, Temp As Point, time As Integer) As Integer
Dim vx As Integer = 0, vy As Integer = 0
If time = 1 Then
Dim sx As String = Convert.ToString(a.X - b.X)
If Math.Abs(a.X - b.X) < 1 Then
Return 1
Else
If sx.Length > 2 Then
vx = (a.X - b.X) \ 100
ElseIf sx.Length = 2 Then
vx = (a.X - b.X) \ 10
Else
vx = 1
End If
End If
Return vx
ElseIf time = 2 Then
Dim sy As String = Convert.ToString(a.Y - b.Y)
If Math.Abs(a.Y - b.Y) < 1 Then
Return 1
Else
If sy.Length > 2 Then
vy = (a.Y - b.Y) \ 100
ElseIf sy.Length = 2 Then
vy = (a.Y - b.Y) \ 10
Else
vy = 1
End If
End If
Return vy
Else
Return 0
End If
End Function
Private Sub button1_Click(sender As Object, e As EventArgs)
button1.Enabled = False
For i As Integer = 0 To 1
Velocity(i) = CheckV(Dest, button1.Location, Temp, i + 1)
Next
timer1.Start()
End Sub
Public Function [Stop](a As Boolean, b As Boolean) …
I dont even know why do you have that while loop there, personally I thinks its pointless, so throw it out of the code. What your code does, its only reading some file. So when it reads, I can go out of this method. Or you want to read it constantly?
If so, you have to create a new thread, and put the code onto it, otherwise the main thread (UI thread) will become inactive (unresponsible).
But reading can be done by avoiding a thread, by just creating a Timer class, which can fires up every some seconds (set Interval property). In a Tick event call gr_log_tail() method.
So, this is mostly it. The While(true) is the problem now.
the problem is in while(true) loop. It seems it takes to infinity (it does not end, becuase you never call false).
Try this:
public static Bitmap BitmapFromWeb(string URL)
{
try {
// create a web request to the url of the image
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
// set the method to GET to get the image
myRequest.Method = "GET";
// get the response from the webpage
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
// create a bitmap from the stream of the response
Bitmap bmp = new Bitmap(myResponse.GetResponseStream());
// close off the stream and the response
myResponse.Close();
// return the Bitmap of the image
return bmp;
} catch (Exception ex) {
return null; // if for some reason we couldn't get to image, we return null
}
}
If you want to access some non-static member inside some class FROM a static method, you need an instance of that class:
class Program
{
private int myFiled = 1;
static void Main(string[] args)
{
//You can NOT do:
int a = myField; //myField is not accessible!!
//what you have to do, is to create a new reference of the class the variable is in:
//so:
Program p = new Program();
int b = p.myField; //this is OK!!
}
//for example, if you have a non-static class:
private void MyMethod()
{
//you can access to class`s members:
int c = myField; //this is OK!!
}
}
The same you do if the field (or some other member) needs to be accessed in some other class.
Hope this is clear enough how to access static members. The bottom line is, that you canNOT access to class members outside of the static class WITHOUT an instance of a class (in our case, an instance is p).
What you you select all (one by one, but all eventually)? Isnt this a bid odd?
Or did you mean something else?
Are these files in one folder? If so, you can get all files from this folder into a FileInfo[] (you need fileInfo, because you need a full path, so set files back where they were before renaiming).
Then you do some additional code of renaiming and use Move method for an actual renaiming:
string path =@"C:\MyFolder";
FileInfo[] files = new DirectoryInfo(path).GetFiles("*.txt");
for (int i = 0; i < files.Length; i++)
{
string newFile = String.Format("{0}{1}.{2}", "File", (i + 1), "txt");
string fullNewPath = files[i].DirectoryName;
File.Move(files[i].FullName, Path.Combine(fullNewPath, newFile));
}
I hope you like it.
Hi, thx mate.
They can be labels, even they are now buttons, and I had in mind do something with them, like coloring just the elements that belong to selected group (all other will be colors differently but the same), so the difference will be visible.
Anyway, there is still a lot of work do to, to implement all the details for each element, but this is mostly in writing text. Then when this is done, only a new form is needed what will show selected element`s details, by reading the appropriate file (or all in one, the appropriate line of text).
And thx for the adivce. I know what you mean (not to use so colorful colors), its hard to read when so-red (and so-green, ...) colors are used. I will consider your advice.
Maybe only the buttons location can be done a bit better, I complicated a bit to much, and this is the only code I dont like... will repair it.
In 1st if statement (If(File.Exists())?? here?
Cant be here, because this line of code does not throw any error. It returns a boolen value (true if file exist, and false if files does NOT exist).
So no error possible.
Tell me where EXACTLY does this happen. Please use a debug mode.
Try using SqlDataAdapter for this job.
Or you can even try using SqlComamndBuilder (of OleDb for Access database instead of Sql):
SqlDataAdapter adapter;
DataSet dataset;
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(Properties.Settings.Default.Database1ConnectionString);//Set the connection to the SQL server
adapter = new SqlDataAdapter("select * from Table1", conn); //Create a DataAdapter instance
dataset = new DataSet();
SqlCommandBuilder builder = new SqlCommandBuilder();//User a CommandBuilder to build insert, update automatically.
builder.DataAdapter = adapter;
adapter.Fill(dataset); //Fill the DataSet
dataGridView1.DataSource = dataset.Tables[0]; //Bind the DataSet to a DataGridView
}
//You can add/remove/modify the Data in the DataGridView
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
adapter.Update(dataset);//Update all the modification to the DataBase
}
You didnt specify where exactly this error occurs, but i assume inthe for loop. Try to change it to:
if (!line.StartsWith("!") && line != "" && !line.StartsWith("#"))
{
//your code...
}
So, what do you wanna know?
A field declared with the static modifier is called a static variable.
Static variables - if they are marked as public they are accessed without a class reference.
For intance:
class class1
{
public static string myVar = "abc";
}
class class2
{
public class2
{
string myVar2 = class1.myVar;
}
}
What else would you like to know?
Done it!
Here is the code, jsut copy and paste it into a brand new project (attention, change project name, so you wont copy complete code of mine to yours created project!!)
You dont need to put anything on the form - keep it empty.
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.IO;
namespace Sep05_PeriodicalTable //CHANGE TO YOUR NAMESPACE!!!
{
public partial class Form1 : Form
{
List<ElementData> elementsList;
List<LegendData> legendList;
Button[] elebuttons;
Button[] legButtons;
public Form1()
{
InitializeComponent();
//path
string fileName = "PeriodicalTable.txt";
string path = Environment.CurrentDirectory;
path = Path.Combine(path, fileName);
//creating new list<T>:
elementsList = new List<ElementData>();
legendList = new List<LegendData>();
//reading file line by line and adding data into list<T>:
string type = null;
foreach (string data in ReadingData(path))
{
if (data == "ELEMENT_LIST")
{
type = "elements";
continue;
}
else if (data == "LEGEND")
{
type = "legend";
continue;
}
if (type == "elements")
SeperateElementData(data);
else if (type == "legend")
SeperateLegendData(data);
}
//Creating phisical periodical table from the data:
CreatingElements();
//Creating legends:
CreatingLegends();
}
private void CreatingElements()
{
elebuttons = new Button[elementsList.Count];
//starting position for 1st upper left button:
int x = 20;
int y = 60;
//and size of buttons:
int size = 48;
foreach (ElementData el in elementsList)
{
if (el.LocationX > 0)
x = 20 + size * el.LocationX;
else
x = 20;
if (el.LocationY > 0)
y = 60 + size * el.LocationY;
elebuttons[el.SequenceNumber - 1] = …
Just did one hell of a job. Did the whole text file with all required data for 118 elemetns.
Now lets create an application which will draw the periodical table :)
:) too much time? hmm, this would be a nice debate to talk about...
No, not too much time, just didnt do anything like it before. But to create a decent Periodical table, its not that simple task. I was thinking of creating a file (*.txt) which will hold of the data, and then just reading it to create the table.
If you want to create the table just by the code, there will be too much of work and too much of the code, because there is nothing "simetrical" about this table.
From the beginning there is a bit more work to create the file (to insert all the data), but when this is done, its only a few minutes of work with the code to make it work.
Hi,
Would you mind to do a big better explanation? From this one I have no clue what do you want.
Thx in advance.
If you want to set the image on some other form, its not good to set it from some other form (over classes). Better to create a new instance of that form, and while in Constructor set it there, using my upper code.
You can use "this" keyword to set the background image property.
this means the form you currently are.
this.BackgroundImage = "your image";
I was bored last night so I created a periodic table form control. Maybe I'll post the code sometime :)
Damn... I forgot to make it. I promised, but completely forgot it.
Will do my version. And looking forward to see yours Momerath.
And what will be the difference between 1st and 2nd rectangle? Will you create n number of rectanlges (and where to position it/them)?
... with the help of mouse by clicking on button line should be displayed on panel and if first rectangle should not b disappeared...
Hi,
I don`t understand these words. Can you please elablrate it better?
Thx in advance.
This is the code that it does what I explained in the post abouve:
int[] numsArr = { 1, 1, 1, 2, 2, 3, 4, 5, 6 };
Dictionary<int, int> dic = new Dictionary<int, int>();
for (int i = 0; i < numsArr.Length; i++)
{
if (dic.ContainsKey(numsArr[i]))
{
dic[numsArr[i]] = ++dic[numsArr[i]];
}
else
dic.Add(numsArr[i], 1);
}
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<int, int> kvp in dic)
sb.AppendLine(String.Format("Number {0} has {1} repetitions.", kvp.Key, kvp.Value));
Console.WriteLine(sb.ToString());
Console.ReadLine();
The best way would be to use a dictionary collection. Key will be an actual number, and Value it`s repetition.
So you wanna have n numbers of listboxes - depending how many subfolder you go into.
Isnt this a bit strange?
It would make sence to show on 1st listbox folders and in 2nd listBox files in this folder (if you are on root - C:, D: then show files from the root in 2nd listbox).
Wouldnt that make more sence?
Create a new UserControl, and "put" ListView inside of it. Position the userControl to the position you want (based on the cell (right) mouse click I think).
Did you sort all the columns? if you change one, you have to re-order all the others. So that two columns wont have same columnIndex maybe.
What do you mean by refresh? Is you mean that the controls are automatially filled up with the appropriate data (based on some selection), then you need to bind each control. You can use DataSource property (for ie. dgv, comboBox, listBox, and set DisplayMember (and ValueMember if needed)) and DataBinding (like you showed in code snippet) to bind data to controls like listBox.
If you did it right, they have to update automatically, without calling any Refresh() method at all.
Tell me more about your issue, and specify your needs and whishes, and where from data are comming (is it from DataTable, or some generic List, or something else).
I would do as Momerat h said. Create a class of one Element, and then create a List<T> which will hold the list of all elements. Class will hold data (properties) specific for each element (Name, Shortname, Number, (and position maybe, because the periodic table is not simetric - for example H is on top left, He is on top right)).
Next, to create a physical table, I would personally choose or labels or buttons. Create one by one, position it (based on the Position property from the element list<T> and place it on the form.
If you need any help, let me know.