Store Datepicker Date Value to Database Birthdate Column in C# ( C sharp ) - datetimepicker

Hey I want to Fetch the date from the date picker and add that date into my database birthdate column
soo plzzz help me out...
here Form View
and Grid View
just tell me syntax how to store the date value in Database birthdate column!
plzzz give me solution in C#.net only...

WinForms: The datepicker has a property called "Value" and it is of DateTime data type. Use that.
Web Forms: if you are using JQuery, just do
var date = $("#myDateControl").val();
Then how you store the value depends on what database you are using (Sql, Oracle, etc) and whether you are using Entity Framework (or other ORM) or not... give more details if you want a more thorough answer.
EDIT
Based on your comments, I would do something like this:
using (var connection - new SqlConnection("my connection string"))
{
using (var command = connection.CreateCommand())
{
command.CommandText = string.Format("INSERT INTO Stu_inf(Enrollno, Firstname, Lastname, Birthdate) VALUES ('{0}', '{1}', '{2}', '{3}')", txtEnrollno.Text, txtFname.Text, txtLname.Text, mtxtBdate.Value.ToString("yyyy-MM-dd"));
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
I wrote this all from memory, so you may get a small syntax error or something.. but that's the idea... hope it helps

Related

how to create a table named "realizations" with another file name? (FoxPro)

I have to create a table with name "Realizations" but it's file must be named like today's date (example "12092016.dbf"). I can get current date from my C# program but how to set the file name in query string???
My data engine is Visual FoxPro.
Is this what you mean? (I assume you mean C# code):
using (var connection = new OleDbConnection(#"Provider=VFPOLEDB;Data Source=c:\My Data Folder"))
{
var cmd = new OleDbCommand(#"select * from Realizations
into table (?)",connection);
cmd.Parameters.AddWithValue("tableName", DateTime.Today.ToString("ddMMyyyy"));
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
Please note that, naming a table like this is not very safe and also a date string in the format ddMMyyyy is not very safe. Maybe you would want to name it like Realizations_20160913. If so then you could say:
cmd.Parameters.AddWithValue("tableName", "Realizations_" +
DateTime.Today.ToString("yyyyMMdd"));

How to change sql generated by linq-to-entities?

I am querying a MS SQL database using Linq and Entity Framework Code First. The requirement is to be able to run a WHERE SomeColumn LIKE '%sometext'clause against the table.
This, on the surface, is a simple requirement that could be accomplished using a simple Linq query like this:
var results = new List<MyTable>();
using(var context = new MyContext())
{
results = context.MyTableQueryable
.Where(x => x.SomeColumn.EndsWith("sometext"))
.ToList();
}
// use results
However, this was not effective in practice. The problem seems to be that the column SomeColumn is not varchar, rather it's a char(31). This means that if a string is saved in the column that is less than 31 characters then there will be spaces added on the end of the string to ensure a length of 31 characters, and that fouls up the .EndsWith() query.
I used SQL Profiler to lookup the exact sql that was generated from the .EndsWith() method. Here is what I found:
--previous query code removed for brevity
WHERE [Extent1].[SomeColumn] LIKE N'%sometext'
So that is interesting. I'm not sure what the N means before '%sometext'. (I'll Google it later.) But I do know that if I take the same query and run it in SSMS without the N like this:
--previous query code removed for brevity
WHERE [Extent1].[SomeColumn] LIKE '%sometext'
Then the query works fine. Is there a way to get Linq and Entity Framework to drop that N from the query?
Please try this...
.Where(x => x.SomeColumn.Trim().EndsWith("sometext"))
Just spoke to my colleague who had a similar issue, see if the following works for you:
[Column(TypeName = "varchar")]
public string SomeColumn
{
get;
set;
}
Apparently setting the type on the column mapping will force the query to recognise it as a VARCHAR, where a string is normally interpreted as an NVARCHAR.

SQL Server datetime culture (localization) headache

SQL Server 2005. Visual Studio 2010. ASP.NET 2.0 Web Application
This is a web application that supports multiple languages, one of them is Korean. I have “langid” in the query string to differentiate different languages, if langid=3 it is Korean.
In my code behind’ C# code, I read a table using this query:
"select * from Reservations where rsv_id = 1234"
There is a column named "rsv_date" in the table which is reservation date, of type datetime. In the db table its value is "11/22/2012 4:14:37 PM". I checked this in SQL server management studio. But when I read it out, I got "2012-11-22 오후 4:14:37"! Where does that Korean “오후” come from??? Is it because of some culture setting anywhere? But I don’t see where, either in my code or in SQL Server. This caused problem for me, because when I modify this record, it will try to write "2012-11-22 오후 4:14:37" to the db, which of course SQL server reports error.
My original code:
Hashtable reservation = new Hashtable();
SqlCommand sqlCommand = null;
SqlDataReader dataReader;
string queryCommand = "select * from Reservations where rsv_id = #RsvID";
sqlCommand = new SqlCommand(queryCommand, getConnection());
sqlCommand.Connection.Open();
sqlCommand.Parameters.AddWithValue("#RsvID", rsvID);
dataReader = sqlCommand.ExecuteReader();
while (dataReader.Read())
{
reservation["rsvID"] = dataReader["rsv_id"];
reservation["rsvCode"] = dataReader["rsv_code"];
reservation["rsvType"] = dataReader["rsv_type"];
reservation["rsvDate"] = dataReader["rsv_date"]; // where does Korean come from?
...
}
It's a common misunderstanding that you can "check" the format of datetime fields in the database.
The format you see on screen will always depend on the client, even if the client is "SQL server management studio".
In the database, the datetime is stored in a binary format that very few need to know.
So, the Korean characters are from the client, in this case your own program.
And Yes, they will depend on some culture setting somewhere.
Your example doesn't show what happens to reservation["rsvDate"] , where is the value displayed with the Korean characters ?
How are you trying to write the value with Korean characters to the database ?
To avoid Korean characters you could use .ToString(CultureInfo.InvariantCulture) where you use the Date value.

Return newly inserted row without having to Submit to database

I need to find a way to get the newly insert row, without previously having to save to the database.
Is there a way? Or I need to keep the whole collection of row in a separated array?
Is this example I adding a row to the table tblConfig, but when I look back in the table the new row is not there.
tblConfig Config = new tblConfig { ID = Guid.NewGuid(), Code ="new config code" };
CTX.tblConfig.InsertOnSubmit(Config);
var Data = from dd in CTX.tblConfig select dd;
this.dataGridView1.DataSource = Data;
After some research , I'll do the work by attaching my LINQ query to a BindingSource object, witch will help me handle with insertion update and so.
Thanks for everyone, for your help :)
Hugo
Could you add that manually like this?
this.dataGridView1.DataSource = CTX.tblConfig.Execute(MergeOption.AppendOnly);

SQL code import into Access 2007

I basically need to know how to import SQL code into Access. I've tried one way but that requires me to do one table and one value at a time which takes a lot of time.
Can anyone help?
If you are trying to import data, rather than SQL code (see Duffymo's response), there are two ways.
One is to go where the data is and dump a .CSV file and import that, as Duffymo responded.
The other is to create a table link from the Access database to a table in the source database. If the two databases will talk to each other this way, you can use the data in the remote table as if it were in the Access database.
Well, some days ago I needed to shift data from an Access database to SQL (reverse of what you're doing). I found it simpler to write a simple script that would read data from my access database and insert it into SQL.
I don't think doing what you need to do is any different.
I don't know if it will help, but I posting my code (It's a simple C# function). You can just change the connections and it will work. Of course I only had 3 fields so I hard-coded them. You can do the same for your db schema.
protected void btnProcess_Click(object sender, EventArgs e)
{
//Open the connections to the access and SQL databases
string sqlDBCnn = #"Data Source=.\SQLEXPRESS;Integrated Security=True;AttachDBFileName=|DataDirectory|\mydb.mdf;user instance=true";
string accessDBCnn = #"Provider=Microsoft.Jet.OleDB.4.0;Data Source=C:\mydb.mdb";
OleDbConnection cnnAcc = new OleDbConnection(accessDBCnn);
cnnAcc.Open();
SqlConnection cnnSql = new SqlConnection(sqlDBCnn);
cnnSql.Open();
SqlCommand cmSql = new SqlCommand("DELETE tablename", cnnSql);
cmSql.ExecuteNonQuery();
//Retrieve the data from the Access Database
OleDbCommand cmdAcc = new OleDbCommand("SELECT * FROM tablename", cnnAcc);
OleDbDataReader drAcc = cmdAcc.ExecuteReader();
using (drAcc)
{
if (drAcc.HasRows)
{
//Loop through the access database records and add them to the database
while (drAcc.Read())
{
SqlCommand cmdSql = new SqlCommand("INSERT INTO tablename(Category, Head, Val) VALUES(#cat,#head,#val)",cnnSql);
SqlParameter parCat = new SqlParameter("cat",System.Data.SqlDbType.VarChar,150);
SqlParameter parHead = new SqlParameter("head",System.Data.SqlDbType.VarChar,150);
SqlParameter parVal = new SqlParameter("val",System.Data.SqlDbType.VarChar);
parCat.Value = drAcc["Category"].ToString();
parHead.Value = drAcc["Head"].ToString();
parVal.Value = drAcc["Val"].ToString();
cmdSql.Parameters.Add(parCat);
cmdSql.Parameters.Add(parHead);
cmdSql.Parameters.Add(parVal);
cmdSql.ExecuteNonQuery();
}
}
}
lblMsg.Text = "<p /> All Done Kapitone!";
}
SQL code? Or data? "one table and one value" makes me think it's the latter. If so, I'd suggest dumping the data out into a .csv file and importing that into Access tables.
Or maybe using a tool like Microsoft's DTS to map and move the data between sources. That would be the best idea.
I guess you are talking about "importing" both structure and data from SQL to ACCESS. ACCESS does not accept standard TSQL scripts that you could generate directly from your SQL Database. There are some commercial products like EMS that can more or less do the job for you. EMS has a data exporter module that can take your SQL data in different formats, including Access.
Another way would be to open an Access file and write some basic VBA code, taking advantage of the DoCmd.TransferDatabase method, where you can link OR copy tables from other databases into Access.
I forgot if these methods also allow the transfer of a 'clean' database model, including primary keys and relations... You'll have to give it a try.