简体   繁体   中英

How do I edit/update records from a database using textbox?

I have a problem and I would like your help. I have in my page an edit button and textboxes. I want to edit one single record from the database to these textboxes. I wrote the following code, when I click the edit button then I have the results. The results load in my textboxes. But when I try again to run the page with the same ID for second time then I have this error 'Specified cast is not valid.' What's going wrong? I used int ID=3; to get the 3rd record in this example

protected void Button2_Click(object sender, EventArgs e)

{

DataClassesDataContext cxt = new DataClassesDataContext(); USER_TABLE aChar = cxt.USER_TABLEs.Single(c => c.ID == 3); //gets a single record

            fname2.Text = aChar.FIRST_NAME;
            lname2.Text = aChar.LAST_NAME;
            pob2.Text = aChar.PLACE_OF_BIRTH;
            pom2.Text = aChar.PLACE_OF_MARRIAGE;
            education2.Text = aChar.EDUCATION;
            occupation2.Text = aChar.OCCUPATION;
            pod2.Text = aChar.PLACE_OF_DEATH;
            String str = aChar.DATE_OF_BIRTH.ToString();
           String str1 = aChar.DATE_OF_MARRIAGE.ToString();
            String str2 = aChar.DATE_OF_DEATH.ToString();

Why are you doing if (!Page.IsPostBack) in your event handler code?

I'd say that normally an event is only raised upon post-back...

I rarely see IsPostBack used in anything other than PageLoad.

您需要明确保存对上下文的更改

cxt.SubmitChanges();

It appears that you are getting a specified cast exception when fetching your object (using Single). You may want to check the data types between your object model and the database to make sure the object isn't expecting numbers where the database uses strings (or vice versa). Also, check the nullability of your objects and database columns. LINQ to SQL does not support implicit type conversions when binding.

As for why it is working on the first request, but not the second, what has changed between the requests? Also, is the context kept alive between the two requests? Single caches the fetched value and short circuits the query pipeline when the same ID is requested a second time, so with Single you should only see one database request if the context was kept alive. Try using ctx.Log = Console.Out to log your database requests, or SQL Profiler if you have it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM