-1

I am trying to get From date and To date in two text boxes using the calender control and then trying to insert this value in a table. How can I proceed with this?? Please help..

string comstr = "insert into ATM_DETAILS_TB values(" + txtpin.Text + ",'" + Convert.ToDateTime(txtvldfrm.Text) + "','" + Convert.ToDateTime(txtvldto.Text) + "'," + Convert.ToInt32(ddlaccno.SelectedValue) + ",'" + Session["strUid"].ToString() + "')";

while using this code it shows error like "String was not recognized as a valid DateTime"

what should I do??

Mark Hall
  • 53,938
  • 9
  • 94
  • 111
raji
  • 65
  • 1
  • 2
  • 9

3 Answers3

2
  1. Use Validation controls to validate that the values in textbox values are valid dates.
  2. Your code us contencating strings directly from user input. This opens you up to all sorts of nasty attacks, the primary being SQL Injection. Use parameterized queries instead.
David
  • 72,686
  • 18
  • 132
  • 173
1

Always use DateTime.TryParse or TryParseExact method to parse the date.

DateTime vldDate;
bool isValid=false;
if(DateTime.TryParse(txtvldfrm.Text,out vldDate))
 {
    isValid=true;
 }
....
if(isValid)
{
  command.Parametter.Add("@vldto",SqlDbType.DateTime).Value=vldDate;
  command.Parametter.Add("@strUid",SqlDbType.VarChar,30).Value=Session["strUid"];
  ..... 
}
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • Hello AVD, thanks for ur reply. how to add parameter for Session["strUid"].ToString() using command.Parametter.Add()? Please help – raji Nov 19 '11 at 14:19
0

You Use from parameterized queries like this:

 string comstr = "insert into ATM_DETAILS_TB values(@pin,@vldfrm,@vldto,@ddlaccno,@strUid)";

    YourCommand.Parametter.AddWithValue("@vldto",Convert.ToDateTime(txtvldto.Text));
    YourCommand.Parametter.AddWithValue("@strUid",Session["strUid"].ToString());
    ....Define the Other Paraametter

Edit----
check this question String was not rec...

Community
  • 1
  • 1
M.Azad
  • 3,673
  • 8
  • 47
  • 77
  • 1
    That won't help with the error he's seeing, but I agree 100% that he should be using parameterized queries. – David Nov 19 '11 at 07:23
  • hi mtaboy, thanks for ur help. I tried the same way u told me.But it shows the same error like ""String was not recognized as a valid DateTime"Please help. – raji Nov 19 '11 at 14:15
  • hi raji. what is your Date column type in your table? – M.Azad Nov 20 '11 at 07:30
  • hi, i created table as below:create table ATM_DETAILS_TB(PK_ATM_DETAILS_ATMID numeric identity(1234,1) primary key,PIN numeric,VALID_FROM datetime,VALID_TO datetime,FK_ATM_DETAILS_USER_ACC_ACCNO numeric references USER_ACC_TB(PK_USER_ACC_ACCNO),FK_ATM_DETAILS_STAFF_USERID varchar(20) references STAFF_TB(PK_STAFF_USERID)) – raji Nov 20 '11 at 17:12
  • are you sure that your date input text is a valid date?and i suggest you a link in my answer – M.Azad Nov 21 '11 at 07:36