.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

How to update a value MS SQL database via code behind

Posted By:      Posted Date: October 24, 2010    Points: 0   Category :ASP.Net


I've been using the code below to read from a database (found on this site a while back), but I'd now like to modify it to UPDATE a value. I'd be grateful if someone could show me how to change it?

            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            string SQL = string.Format("SELECT OfficialID, Official_FirstName, Official_LastName FROM tbl_Officials WHERE OfficialID = " + QueryString_OfficialID);
            System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand();
            System.Data.SqlClient.SqlDataReader dr = null;

            string Official_FirstName = "";

            using (conn)
                    comm.Connection = conn;
                    comm.CommandType = System.Data.CommandType.Text;
                    comm.CommandText = SQL;
                    dr = comm.ExecuteReader();
                    while (dr.Read())
                        Official_FirstName = dr["Official_FirstName"].ToString();
                catch (Exception ex)

View Complete Post

More Related Resource Links

Where to place code to update database using WPF in VS2010?


I have an app in WPF that has numerous controls that are bound to datatables that are filled from sqlserver.

I now need to add the code for updates, inserts and deletes

Where should I put the code to implement this?

I found code


._adapter.UpdateCommand.CommandText = "tool generated update command

in an auto-generated section of the source file that VS created it looks almost correct but I have never before seen an update statement with an order by clause.
I also found multiple instances of:
  if ((this .Adapter.UpdateCommand != null )) {
 this .Adapter.UpdateCommand.Connection = value ;             }
But I cannot find where value is defined or assigned
I have a tabbed interface with a selection list to move back and forth through the datatable. I want to update the data base with all changes to the current selection when a user changes selection or selects a different tab So what is the preferred method to initiate the update and where should

Can this code be setup to run against the whole database instead of just 1 record at a time?


We have made some changes to this code to start capturing 1 new field of data and updating it as new records are added. But there is currently about 120,000 records more or less.. those records of course dont have the new field populated with anything..

We would like to run this logic that already in place and run it against the tables to update the fields 1 time. I think to make it easier, if it can be setup to expect the "valueTwo" variable, so that we can run it againt the individual codes instead of doing all the records at one time.. there are codes that only have a few records, so it would be best to test initially against the small code group.


            strSqual = "insert into trans (trans_type_name, trans_date,sys_id,mod_user_id,show_ind, remoteCode, techName) values('" & valueTwo & "','" & TransDate & "',"&strSystemID&", 1,'T', '" & dbQuote(strUser) & "', '" & strTechName & "')"        
            'get the new transaction_id out for just inserted alarm   
            strSqual = "select max(transaction_id) as transaction_id from trans"  
            set rst = getStaticRecordSet(strSqual)

Create/add table from code to database



I create table:

                  DataSet data=new DataSet();

                  DataTable myTable = new DataTable("NewTable");

                   DataColumn[] keys = new DataColumn[1];

                   // create column
                   keys[0] = new DataColumn();
                   keys[0].DataType = System.Type.GetType("System.String");
                   keys[0].ColumnName = "PointID";
                   myTable.Columns.Add(keys[0]);    &nb

Under the Table: How Data Access Code Affects Database Performance


In this article, the author delves into some commonly used ways of writing data access code and looks at the effect they can have on performance.

Bob Beauchemin

MSDN Magazine August 2009

Toolbox: Database Audit Logs, Joel on Software, Code Handouts, and More


This month the Toolbox column takes a look at database logging, Joel Spolsky's blog, printing code projects, and ASP.NET reading.

Scott Mitchell

MSDN Magazine May 2008

Protect It: Safeguard Database Connection Strings and Other Sensitive Settings in Your Code


Protecting application secrets, such as database connection strings and passwords, requires careful consideration of a number of pertinent factors such as how sensitive the data is, who could gain access to it, how to balance security, performance, and maintainability, and so forth. This article explains the fundamentals of data protection and compares a variety of techniques that can be used to protect application settings. The author discusses what to avoid, such as hiding keys in source code and the use of Local Security Authority. In addition, he presents some effective solutions such as the Data Protection API.

Alek Davis

MSDN Magazine November 2003

Wicked Code: Supporting Database Cache Dependencies in ASP.NET


Developers love the ASP. NET application cache. One reason they love it is that ASP. NET lets them create dependencies between items placed in the cache and files in the file system. If a file targeted by a dependency changes, ASP.

Jeff Prosise

MSDN Magazine April 2003

update user status in database when ever user logoff


actually i came across this senario for new project where userstatus must change to log off when ever he do fallowing activity.I have maintain user status when he log in to web based system.

Activities are


1.user click log off

2.or user click browser close button or close brwoser tab.

3.or Fource fully shut down his Pc

I am able to get first 2 but not the last one.I googled it but not get any satified ans for that.

I m looking for guidens for this. Any help is grate help for me as i want it.And also other suggesstion also welcomed.

thanks in advance


execute update timedout expires , table with trigger due to recovery of database


I have table A in database A  , in table A i have trigger to insert record to database B table A, each update and insert of database A -table A, triiger fire and insert record in database B table A, when i try to update some times asp.net application gives error

"Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding."

and then error log says System.Data.SqlClient.SqlException: Database 'database B is being recovered. Waiting until recovery is finished.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean ret

Update Profile Database from text file using BDC



I have a requirement to import the profile properties from a text file in sFTP to update the MOSS Profile Database. The objective is to create a single repository for the Staff Directory in MOSS.

Can I use BDC to connect and update the Profile database?

What is the alternate approach?


Failed to update database "Hist_OHLC_ASnapshot" because the database is read-only.

Hi there, I've got this ExecutionfailureException using the subroutine below. It's been suggested by Alok.   public void CreateSnapshotAlok ( string SourceDatabaseName )         {             ProvideSecurity.provideSecurity ( );             DoServer.GetSrvConnOrSwitch ( "master" );             /* This is to ensure that a database with same name does not exist which is not needed if one chooses unique name for snapshot each time.*/             if ( Globals.srv.Databases[ SourceDatabaseName + "_Snapshot" ] != null )             {                 Globals.srv.Databases[ SourceDatabaseName + "_Snapshot" ].Drop ( );             }             Database database = Globals.srv.Databases[ SourceDatabaseName ];             Database snapshot = new Database ( Globals.srv, SourceDatabaseName + "Snaps

Error code 737D-Trying to download update

My computer is recommending that I download this: Security Update for SQL Server 2005 Service Pack 3 (KB970892) But it tells me this: Installation status: Failed Error details: Code 737D Update type: Important A security issue has been identified in the SQL Server 2005 Service Pack 3 that could allow an attacker to compromise your system and gain control over it. You can help protect your computer by installing this update from Microsoft. After you install this item, you may have to restart your computer. System: Windows Vista Home Premium Service Pack 2 HP Pavilion dv6700 notebook PC 32-bit Operating System Any ideas???  

Failed to initialize MSDB database for tuning (exit code: -1073741819). (DTAClient)

Hello,This is the first time I am using this forum. I am stuck and need some help. I received this error message both on SQL 2005 and 2008. I am currently using SQL 2008 DEV for testing purposes and I am experiencing this error message when trying to connect to Database Engine Tuning Advisor. I am using the SA account so I should not have any security issues. Also this is a fresh install of SQL 2008 DEV on a fresh install of Windows XP Pro with all SP. Can some please help.Error:"Failed to initialize MSDB database for tuning (exit code: -1073741819). (DTAClient)"=================================== Failed to open a new connection. =================================== Failed to initialize MSDB database for tuning (exit code: -1073741819). (DTAClient) ------------------------------Program Location:    at Microsoft.SqlServer.Management.DTA.Client.TuningServer.InitializeTuningParametersDatabase()   at Microsoft.SqlServer.Management.DTA.Client.TuningServer.InitializeConnection()   at Microsoft.SqlServer.Management.DTA.Client.TuningServer.Connect()   at Microsoft.SqlServer.Management.DTA.Shell.SessionMonitor.AddServerInternal(SqlConnectionInfo connectionInfo, SqlConnection connection)   at Microsoft.SqlServer.Management.DTA.Shell.SessionMonitor.AddServer(SqlConnectionInfo connectionInfo, SqlConnection connection)   at Microsoft.SqlServer.Management.DTA.Shell.SessionMonitor.On

Update Database Schema without redeployment in Entity Framework

Hello. we build an app with 2 layers i.e the presentation and the Business layer which holds the business logic and have the entity framework provide us wtih entities. my question here is is there a way we can change the database schema and not have to redeploy the app to the client.  

Why is it that this code updates my sql database with the default EditBox text?

Any help is appreciated. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using MySql.Data.MySqlClient; public partial class _Default : System.Web.UI.Page { TextBox EditBox = new TextBox(); TableRow[] NewRows = { new TableRow(), new TableRow() }; TableCell[] NewCells = { new TableCell(), new TableCell() }; string ID; protected void Page_Init(object sender, EventArgs e) { } protected void Page_Load(object sender, EventArgs e) { var Connection = new MySqlConnection("Server=localhost;Database=site;Username=root;Password=root"); var Command = new MySqlCommand("select * from news", Connection); Connection.Open(); var Reader = Command.ExecuteReader(); while (Reader.Read()) { ID = Reader.GetString("ID"); string Title = Reader.GetString("Title"); string Text = Reader.GetString("Text"); foreach (TableRow Row in NewRows) { NewsTable.Rows.Add(Row); } NewCells[0].Text = Title; NewCells[1].Text = Text; NewCells[0].Font.Bold = true; NewCells[0].Font.Underline = true; NewCells[0].Font.Size = Fon

Sharepoint Designer update which database

Whenever you are making changes using Sharepoint Designer, which content database is going to be update or which database maintain the information whenever you made the change thri sharepoint designer?

Update Database Record using GridView and Stored Procedure

Hi, I am trying to update record via stored procedure, but i got error at very start point. Problem is when i click on Edit link button within the Gridview it produce error. I can populate values from database fine but its produce error when i click on edit link button. Please see the code below. *********** ASP.net GridView Code I am using *****************<asp:GridView ID="GridView1" runat="server" DataKeyNames="RollID, EmpID" AutoGenerateColumns="False" Width="700px"> <Columns> <asp:TemplateField HeaderText="ApplicationID" Visible="false"> <ItemTemplate> <asp:Label ID="AppsID" runat="server" Visible="false"><%# Eval("RollID") %>'</asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="ReleaseID" Visible="false"> <ItemTemplate> <asp:Label ID="rlsID" runat="server" Visible="false"><%# Eval("EmpID") %></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Roll Name"> <ItemTemplate> <asp:Label ID="rlsVersion" runat="server"><%# Eval("Roll_Name")%></asp:Label> </ItemTemplate> <EditI
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend