|
Good catch, still needs to implement proper disposal methods though when working with COM objects like OPC servers
|
|
|
|
|
The question is given. Which one's faster? I would think the second one, but I am not sure.
|
|
|
|
|
This SO post may help you[^] - However I doubt if list.First() does anything else than
return list[0];
so list[0] may be marginally faster. As explained in the post, the main difference is the kind of Exception you get when no element is in the list.
cheers,
Marco
|
|
|
|
|
if you can call
var item = list[0]
it's probably faster than calling
var item = list.First()
This is the code of the First Extension
public static TSource First<TSource>(this IEnumerable<TSource> source) {
if (source == null) throw Error.ArgumentNull("source");
IList<TSource> list = source as IList<TSource>;
if (list != null) {
if (list.Count > 0) return list[0];
}
else {
using (IEnumerator<TSource> e = source.GetEnumerator()) {
if (e.MoveNext()) return e.Current;
}
}
throw Error.NoElements();
}
The First method is a LINQ-Extension and is used for IEnumerable. Not all IEnumberable implementations do support the direct access of elements through an index (As IEnumberable does not have a method implemented for it).
IEnumberable gets implemented by nearly all of the .NET Collections, Lists or Arrays. So you don't have to care if you can access it directly with the index or not.
|
|
|
|
|
Directly accessing the element is faster, if there are elements in the list. However, what about if there are no elements? What happens then? Of course, both cases would result in an exception, which is where the oddity comes into play that is, at this point it's probably faster to call FirstOrDefault if the list can be null. Of course, where things get interesting is the fact that list[0] might contain a value, but it might not be the one that you're interested in, because First is designed to work as a Linq expression, so it can return you the item that is at a certain location based on the results of your Linq query.
|
|
|
|
|
LINQ is quicker to write but not necessarily always faster.
|
|
|
|
|
HI ,
even after inserting different patient id on windows form and when clicked save button.
I am getting an Error :
<pre lang="css">An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Violation of PRIMARY KEY constraint 'pk_patienid'. Cannot insert duplicate key in object 'dbo.patient'.
The statement has been terminated.</pre>
even after inserting different patient id on windows form and when clicked save button.
my code is :
private void button1_Click(object sender, EventArgs e)
{
resetLabels();
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=Q:\Dotnet\dental1\dental1\patientdb.mdf;Integrated Security=True;User Instance=True";
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "select convert(varchar(50),getdate(),105) as date";
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
date = sdr["date"].ToString();
}
sdr.Close();
setPatientidtxt();
if (updateflag)
{
cmd.CommandText = "update Patient set" +
" name=@FirstName,surname=@LastName,age=@Age,city=@City,gender=@Gender,allergy=@Allergy,phoneno=@ContactNo,consultingfees=@Fees,note=@Note,date=@Date,time=@Time" +
" where patientid=@Patientid";
cmd.Parameters.AddWithValue("@Patientid", Convert.ToInt64(textBox1.Text));
}
else
{
cmd.CommandText = "insert into patient (patientid,name,surname,age,city,gender,allergy,phoneno,consultingfees,note,date,time) values" +
"(@patientid,@FirstName,@LastName,@Age,@City,@Gender,@Allergy,@ContactNo,@Fees,@Note,@Date,@Time)";
}
cmd.Parameters.AddWithValue("@patientid", textBox1.Text);
cmd.Parameters.AddWithValue("@FirstName", textBox2.Text);
cmd.Parameters.AddWithValue("@LastName", textBox3.Text);
cmd.Parameters.AddWithValue("@Age", textBox4.Text);
cmd.Parameters.AddWithValue("@City", textBox5.Text);
//radio button
if (radioButton1.Checked == true)
{
cmd.Parameters.AddWithValue("@Gender", radioButton1.Text);
}
else
{
cmd.Parameters.AddWithValue("@Gender", radioButton2.Text);
}
if (radioButton3.Checked == true)
{
cmd.Parameters.AddWithValue("@Allergy", radioButton3.Text);
}
else
{
cmd.Parameters.AddWithValue("@Allergy", radioButton4.Text);
}
cmd.Parameters.AddWithValue("@ContactNo", textBox6.Text);
cmd.Parameters.AddWithValue("@Fees", textBox7.Text);
cmd.Parameters.AddWithValue("@Note", textBox8.Text);
cmd.Parameters.AddWithValue("@Date", System.DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("@Time", System.DateTime.Now.ToLongTimeString());
cmd.ExecuteNonQuery();
button4.Enabled = true;
label11.Visible = true;
label4.Visible = true;
timer1.Start();
}
}
only first time data is saved in database: and ome colums as 0
patientid name surname age city gender allergy phone no consultationfes date time
0 0 Male No 0 0 07-05-2013 00:23:06
NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
|
|
|
|
|
So, I take it that patientid is the primary key here. I also bet you haven't set it up to be an auto incrementing number (an identity column). Open the table up in SQL Server Manager, click on the column and check the properties on that column. Set it to be identity. Finally, amend your insert query so that it doesn't attempt to pass in a patientid - if it's auto incrementing, you don't need to specify the column when you enter it.
Now, when you enter code, use the pre block to mark the code only. So, to get this:
public void DoSomething(int counter)
{
} Your message would look like this
<pre lang="c#">public void DoSomething(int counter)
{
}</pre>
|
|
|
|
|
Hello thanks for the help.
I had forgotten to put identity on primary key patientid
but after setting an identity,by giving the property to Patientid textbox as enable=false. when i run windows form ,the patient id textbox is blank and after entering details of all text box,radiobutton etc when i click save button the data vanishes and only patient id is displayed on form in the increasing no.I had not yet put any validation now.
also want to know ho do i reset the identity,is like "dbcc identity"
also only patient id is taken in database and rest column are taking as "0" and some as lank as pasted in question.
modified 5-Jul-13 4:58am.
|
|
|
|
|
you are inserting a record with an already existing primary key value (patientid).
I would put a break point on the insert statement check to see what the patientid is and then manually check to see if that value exists in the database
Every day, thousands of innocent plants are killed by vegetarians.
Help end the violence EAT BACON
|
|
|
|
|
ok i will try for the same.
Thanks.
|
|
|
|
|
Hi,
I am having trouble shuffling a column out of two. This is my original table below in Ms Access.
ID_EMPLOYEE ID_STATION
ALAD DECH
FRED DECI
MIKE ORR
PAM OR
RAK ORW
RAYN PROC
I would like to shuffle ID_STATION and have something different at every run. For example:
ID_EMPLOYEE ID_STATION
ALAD ORW
FRED PROC
MIKE DECI
PAM DECH
RAK OR
RAYN ORR
I am using visual studio 2012 with c#.
I created a List called scheduleList in my class SCHEDULE which contains properties like sEmployeeID and sStationID . I fill the list as follow:
List<SCHEDULE> scheduleList = new List<SCHEDULE>();
foreach (DataRow row2 in tschedule.Rows)
{
sEmployeeID = row2["ID_EMPLOYEE"].ToString();
sStationID = row2["ID_STATION"].ToString();
scheduleList.Add(new SCHEDULE(sEmployeeID, sStationID));
}
All I want now is a code to shuffle my ID_STATION only.
modified 4-Jul-13 16:26pm.
|
|
|
|
|
Create a table that holds "all possible values" or "testset" that can go into the ID_STATION, use RANDOM to fetch the values for your insert.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
You could do this as below:
1. Create a new List to store all values of ID_STATION
2. Use Random class to generate a random index from 0 to upper bound value of the above List
3. Add the value corresponding to this index into a new List
4. Remove the value from the old List
5. Repeat from 2 until the old List become empty.
6. Update every record in your table
Update tableName set ID_STATION = stationList[i] where ID_EMPLOYEE = employeeList[i]
"Never memorize something that you can look up." - Albert_Einstein
|
|
|
|
|
I'm working on a string and I want to split my string in multiple strings.
e.g.- my string is String str = "Data + Value + object + system";
I want new strings like String str1 = "Data";
str2 = "Value";
str3 ="object";
str4 = "system";
How can I do this?
|
|
|
|
|
Try the String.Split method[^]:
String str = "Data + Value + object + system";
String[] parts = str.Split(new[]{ " + " }, StringSplitOptions.None);
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
|
There's a HOWTO[^] on MSDN. It uses a "local data cache", which means that it's actually looking up the details in a local database.
Wouldn't it be easier to simply put some name/passwords in a normal database and authenticate against that?
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
The reason i want to use the ASP.NET SqlMembershipProvider is because in the near future, an ASP.NET application will be developed off the same database and the user access rules and permissions will be required to be the same as in this win forms application.
|
|
|
|
|
EricCiz wrote: an ASP.NET application will be developed off the same database Start with the ASP.NET application; it doesn't need to do much, except allow you to login. That way it'll be easier to integrate the WinForm app on the authentication-mechanism of the ASP.NET app, since you'd be re-using the existing structure.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Hi,
I am developing an application in which various forms are available and user had to add details on that forms and save in sql.on every form i have to save 5-6 textbox data.should i use executenonquery or execute scalar. also want to know the difference between two.
|
|
|
|
|
|
thanks for the help
|
|
|
|
|
private void button1_Click(object sender, EventArgs e)
{
resetLabels();
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\patientdb.mdf;Integrated Security=True;User Instance=True";
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "select convert(varchar(50),getdate(),105) as date";
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
date = sdr["date"].ToString();
}
sdr.Close();
setPatientidtxt();
if (updateflag)
{
cmd.CommandText = "update Patient set" +
" name=@FirstName,surname=@LastName,age=@Age,city=@City,gender=@Gender,allergy=@Allergy,phoneno=@ContactNo,consultingfees=@Fees,note=@Note,date=@Date,time=@Time" +
" where patientid=@Patientid";
cmd.Parameters.AddWithValue("@patientid",textBox1.Text);
}
else
{
cmd.CommandText = "insert into patient values" +
"(@FirstName,@LastName,@Age,@City,@Gender,@Allergy,@ContactNo,@Fees,@Note,@Date,@Time)";
}
cmd.Parameters.AddWithValue("@FirstName", textBox2.Text);
cmd.Parameters.AddWithValue("@LastName", textBox3.Text);
cmd.Parameters.AddWithValue("@Age", textBox4.Text);
cmd.Parameters.AddWithValue("@City", textBox5.Text);
//radio button
if (radioButton1.Checked == true)
{
cmd.Parameters.AddWithValue("@Gender", radioButton1.Text);
}
else
{
cmd.Parameters.AddWithValue("@Gender", radioButton2.Text);
}
if (radioButton3.Checked == true)
{
cmd.Parameters.AddWithValue("@Allergy", radioButton3.Text);
}
else
{
cmd.Parameters.AddWithValue("@Allergy", radioButton4.Text);
}
cmd.Parameters.AddWithValue("@ContactNo", textBox6.Text);
cmd.Parameters.AddWithValue("@Fees", textBox7.Text);
cmd.Parameters.AddWithValue("@Note", textBox8.Text);
cmd.Parameters.AddWithValue("@Date", System.DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("@Time", System.DateTime.Now.ToLongTimeString());
// here the exception error (break) is comming at ExecuteNonQuery)
cmd.ExecuteNonQuery();
button4.Enabled = true;
label11.Visible = true;
label4.Visible = true;
timer1.Start();
}
}
I am getting an error as :
"An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Column name or number of supplied values does not match table definition."
and sequence of columns in my table is (patientid,name,surname,age,city,gender,allergy,phoneno,consultingfees,note,date,time)
i am wondering where is sequence wrong in my code. .
|
|
|
|
|
for insert add column names before values keyword like below
cmd.CommandText = "insert into patient (patientid,name,surname,age,city,gender,allergy,phoneno,consultingfees,note,date,time) values" +
"(@FirstName,@LastName,@Age,@City,@Gender,@Allergy,@ContactNo,@Fees,@Note,@Date,@Time)";
check column name and paremeter sequence. they should math number and each columns datatype should match with parametere
|
|
|
|
|