How To Programmatically Construct The UpdateCommand For SqlDataSource

Aug 1, 2007

Hi, All

I'm using Gridview and SqlDataSource to dynamically display the contents in different tables, as followed:

<%
   dataSource.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["connectionString"];
   dataSource.SelectCommand = "SELECT * FROM " + tableName;
   gridView.DataBind();

   dataSource.UpdateCommand = "";
%>


<asp:SqlDataSource ID="dataSource" runat="server"></asp:SqlDataSource>

<asp:GridView ID="gridView" runat="server" DataSourceID="dataSource" AllowPaging="True" AllowSorting="True" AutoGenerateEditButton="True" BorderColor="Silver" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" PageSize="20" DataKeyNames="ID" OnRowDataBound="tableGridView_RowDataBound">
    <HeaderStyle BackColor="#C0C0FF" />
    <AlternatingRowStyle BackColor="#C0FFC0" />
</asp:GridView>


The datasource take the "tableName" as argument to determine which table to display. My problem is I can't figure out a way to programmatically construct the UpdataCommand for the SqlDataSource. I try to get the field names from the HeaderRow, but all the cells are empty in this row.

Does anyone know what causes the problem or how to construct the UpdateCommand properly. Thanks!

View 3 Replies


ADVERTISEMENT

UpdateCommand For SQLDataSource

Apr 13, 2007

I have a custom setup so bear with me here in my explanation.  The SelectCommand for my SQLDataSource gets data from a table using a QueryString for filtering by the record ID. A Repeater control is then used to populate the data into different Textboxes on the page (and a custom HTML-editor control). This works 100%.  I'm trying to use the UpdateCommand for the SQLDataSource to then update the record with the data that the user changes. (Example: FieldA is "foo" and the user changes it to "foobar". When the form is submitted, it then updates FieldB to be "foobar").  The form is being submitted, but the data isn't being updated at all.  Any ideas? Thanks for the help in advance. 

View 11 Replies View Related

Sqldatasource.updatecommand

May 11, 2006

I have a SQLDataSource that has an UpdateCommand assigned to it.  At certain times I may need to change the UpdateCommand to save different info to the database.  I thought I would be able to use sqldatasource.updatecommand.equals() to change the UpdateCommand and then call the sqldatasource.update method, but it didn't work...the default command was still used.  Is there something else I need to change?  I figured my next option would be to create another sqldatasource.  Any help would be great!

View 4 Replies View Related

UpdateCommand In Sqldatasource Control

Oct 15, 2007

Hello all,
I am trying to update the record which involed the modification of key in Datakeynames, but when i click the update button from gridview, it doesn't allow to change the value of modified column.
<asp:SqlDataSource ID="SqlDataSource1" runat="server" DataSourceMode="DataSet"                 ConnectionString="<%$ ConnectionStrings:WebsiteDataConnection %>" OldValuesParameterFormatString="old_{0}"                SelectCommand="SELECT * FROM [ServiceAgents]"                InsertCommand="INSERT INTO ServiceAgents VALUES(@Ser_STATE, @Ser_CITY, @Ser_AGENT, @Ser_PHONE, @Ser_EQUIPMENT)"                UpdateCommand="UPDATE ServiceAgents SET AGENT=@AGENT, PHONE=@PHONE WHERE (STATE=@STATE and CITY=@CITY and AGENT=@old_AGENT and EQUIPMENT=@EQUIPMENT)"                DeleteCommand="DELETE FROM ServiceAgents WHERE (STATE=@STATE and CITY=@CITY and AGENT=@AGENT and EQUIPMENT=@EQUIPMENT)" >                                <UpdateParameters>                    <asp:Parameter Type="String" Name="AGENT" />                    <asp:Parameter Type="String" Name="PHONE" />                                         <asp:Parameter Name="old_AGENT" />                    <asp:Parameter Type="String" Name="STATE" />                    <asp:Parameter Type="String" Name="CITY" />                    <asp:Parameter Type="String" Name="EQUIPMENT" />                </UpdateParameters>                                <InsertParameters>                    <asp:ControlParameter Name="Ser_STATE" ControlID="TextBox_state"/>                    <asp:ControlParameter Name="Ser_CITY" ControlID="TextBox_city"/>                    <asp:ControlParameter Name="Ser_AGENT" ControlID="TextBox_agent"/>                    <asp:ControlParameter Name="Ser_PHONE" ControlID="TextBox_phone"/>                    <asp:ControlParameter Name="Ser_EQUIPMENT" ControlID="TextBox_equip" />                   </InsertParameters>                                <DeleteParameters>                   <asp:Parameter Type="String" Name="STATE" />                    <asp:Parameter Type="String" Name="CITY" />                    <asp:Parameter Type="String" Name="AGENT" />                    <asp:Parameter Type="String" Name="EQUIPMENT" />                </DeleteParameters>                            </asp:SqlDataSource>
Does anyone got any ideas about it? Where is wrong in the control?

View 3 Replies View Related

SqlDataSource UpdateCommand Plus Insert

Oct 22, 2007

SqlDataSource UpdateCommand plus Insert
I have a SqlDataSource with an UpdateCommand but besides that i need also an Insert command triggered on the same update command.
That´s because i need to update a record and at the same time include a log of that update in another database.
Thanks

View 3 Replies View Related

SqlDataSource && DetailsView UpdateCommand

Mar 6, 2006

Hi
I have a Page with a DetailsView and SqlDataSource. When Editing the DetailsView the Sql;DataSource UpdateCommand does not seem to pick up the @parameters of the form fields. I have used OnItemUpdating to view all Keys/OldValues/NewValues passed into the UpdateCommand but nothing seems to be picked up.
When I place a value into UpdateCommand it updates correctly but does not when I use the form. At this stage I have simplified the code down to typical Master-Details Pages (Separate) using a QueryString to filter the SelectCommand. But nothing seems to work.
Please help! I have wasted so much time trying to resolve this and I am on deadline and need this to work.
Thanks
Dave

View 3 Replies View Related

SQLDataSource: Update 2 Tables With 1 UpdateCommand?

Mar 16, 2007

I have a Gridview (edit enabled), connected to a SQLDataSource.
 SQLDataSource populates the gridview from 1 SelectCommand.
 figure1:
ColumnA | ColumnB | ColumnC
 
I have 2 SQL Server 2005 tables: Table1 and Table2 
Now on my SQLDataSource's UpdateCommand, I want the value of ColumnB to go to Table1's ColumnB, and ColumnC to go to Table2's ColumnC.
How do I do this?
I understand I can't do this with 1 UPDATE-SET sql query. Maybe I can with stored procs or something, but im kinda noobish when it comes to this. How? Thanks

View 1 Replies View Related

GridView Update, With SqlDataSource UpdateCommand Set From Code-behind. (C#)

Mar 9, 2006

Hi all
I have a GridView on an aspx page, that is enabled for editing, deletion and sorting.
In the Page_Load event of the aspx page, i add a SqlDataSource to the page, and bind the source to the GridView.
When i click the update, or delete button, it makes a PostBack, but nothing is affected. I'm sure this has got something to do with the parameters.
First, i tried having the GridView.AutoGenerateColumns set to True. I have also tried adding the columns manually, but no affect here either.
The code for setting the commands, and adding the SqlDataSource to the page are as follows:
            string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;            string strProvider = ConfigurationManager.ConnectionStrings["ConnectionString"].ProviderName;            string selectCommand = "SELECT * FROM rammekategori";                        SqlDataSource ds = new SqlDataSource(strProvider, strConn, selectCommand);            ds.ID = "RammeKategoriDS";            ds.UpdateCommand = "UPDATE rammekategori SET Kategoribeskrivelse = @Kategoribeskrivelse WHERE (Kategorinavn = @Kategorinavn)";            ds.DeleteCommand = "DELETE FROM rammekategori WHERE (Kategorinavn = @Kategorinavn)";                        Parameter Kategorinavn = new Parameter("Kategorinavn", TypeCode.String);            Parameter Kategoribeskrivelse = new Parameter("Kategoribeskrivelse", TypeCode.String);            ds.UpdateParameters.Add(Kategorinavn);            ds.UpdateParameters.Add(Kategoribeskrivelse);            ds.DeleteParameters.Add(Kategorinavn);
            Page.Controls.Add(ds);
            SqlDataSource m_SqlDataSource = Page.FindControl("RammeKategoriDS") as SqlDataSource;
            if (m_SqlDataSource != null)            {                this.gvRammeKategorier.DataSourceID = m_SqlDataSource.ID;            }
As mentioned - no affect at all!
Thanks in advance - MartinHN
 

View 4 Replies View Related

Creating SQLDataSource Programmatically?

Apr 17, 2007

Hello. Im trying to create an SQLDataSource control programmatically. I need to do this because I want to do some stuff on my MasterPage's 'Page_Init' event.
 heres my code (Master.master.vb): Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
lblUser.Text = Page.User.Identity.Name

Dim PUser As New ControlParameter
PUser.ControlID = "lblUser"
PUser.Name = "LoginName"
PUser.PropertyName = "Text"
PUser.Type = TypeCode.String
PUser.DefaultValue = Page.User.Identity.Name

Dim SQLDS_Login As New SqlDataSource
SQLDS_Login.ID = "SQLDS_Login"
SQLDS_Login.ConnectionString = "I put conection string here. How do I use the one on my web.config?"
SQLDS_Login.SelectCommand = "SELECT [LoginID], [LoginName], [Role], [Status] FROM [myLogin] WHERE ([LoginName] = @LoginName)"
SQLDS_Login.SelectParameters.Add(PUser)
SQLDS_Login.SelectCommandType = SqlDataSourceCommandType.Text

GridView1.DataSource = SQLDS_Login
GridView1.DataBind()

End Sub
 
When i run, i get this error message:
The SqlDataSource control 'SQLDS_Login' does not have a naming container.  Ensure that the control is added to the page before calling DataBind.
 I never had any problem with Inserts, Updates and Deleting, but I have never made it work for Select when doing it programmatically.
Can you help me with this?

View 1 Replies View Related

Programmatically Add ArrayList Into To Sqldatasource.

Jul 15, 2007

I am trying to add a number of dates into a Sql database.  Basically I want the user to add the start and end date and then all the dates in between are are added to a database in unique records. I can create an ArrayList but I don't know how to bind it to an SqlDataSource   Dim startdate As DateTime = tbstartdate.Text Dim enddate As DateTime = tbenddate.Text Dim datediff As TimeSpan = enddate.Subtract(startdate) Dim noofdays As Integer = datediff.Days Dim ar As New ArrayList Dim i For i = 0 To noofdays ar.Add(startdate.AddDays(i)) Next Sorry if this is a total noob question.... 

View 1 Replies View Related

Programmatically Specify SqlDataSource Parameters

Apr 27, 2006

I have a GridView bound to a SqlDataSource. On page load I would like to programmatically specify a SelectParameter value based on the role of the user. This SelectParameter will be used in my WHERE clause. The closest post I can find is http://forums.asp.net/thread/1233258.aspx but no answer was posted.
What code would I use to modify a SelectParameters value? Is it possible to reference a parameter by name (SqlDataSource1.SelectParameters["usertype"]) or does it have to be by index? (SqlDataSource1.SelectParameters[0])
Alternatively, perhaps I'm going about this in the wrong way, is there a better way to have dynamic GridView content based on the role of the user?
Thank you very much for your help.

View 3 Replies View Related

Refresh An SQLDataSource Object Programmatically

Oct 27, 2006

Background - I have a page that uses a numeric value stored in a Session object variable as the parameter for three different SQLDataSource objects, which provide data to two asp:Repeaters and an asp:DataList.  Also, in the Page_Load, I use this value to to seed a stored procedure and an SQLDataReader to populate several unbound Labels.  This works fine.  In addition, I have a collection of 6 TextBoxes, an unbound Listbox, and two Buttons to allow the user to do searching and selection of potential matches.  This basically identifies a new numeric value that I store in the Session variable and PostBack the page (via one of the buttons).  This also works fine.Problem - I have been tasked with taking a different page and adding six textboxes to collect the search values, but to post over to this page, populate the existing search-oriented TextBoxes, adn programmatically triggering the search.  Furthermore, I have to detect the number of matching records and, if only 1, have the Repeaters and DataList display the results based on the newly selected record's key numeric value, as well as populating the unbound Labels.  I have managed to get all of this accomplished except for programmatically triggering the Repeaters and DataList "refresh".  These controls only populate as expected if a button is clicked a subsequent time, which makes sense, since that would trigger a PostBack and the Page_Load uses the new saved numeric key value from the Session.My history in app development is largely from Windows Forms development (VB6), this is my second foray into Web Form dev with ASP.NET 2.0.  I am willing to acceptthat what I am trying to do does not fit into the ASP environment, but I have to think that this is something that has been done before, and (hopefully) there is a way to do what I need.  Any ideas, oh great and wise Forum readers? *smile* 

View 3 Replies View Related

Help: Programmatically Update Data From An SQLDataSource (C#)

Jul 3, 2007

ello all
 Would someone be so kind as to save me from getting balder through pulling my hair out.
My aim is to extract data from a database using SQLDataSource, then edit the data and update the database using the SQLDataSource.
I have achieve the problem of retrieving the data from the sqlDataSource:DataView openRemindingSeats = (DataView)SqlDataSource2.Select(DataSourceSelectArguments.Empty);        //Int32 openRemindingSeats = SqlDataSource2.Select(DataSourceSelectArguments.Empty), DataView;
        foreach (DataRowView rowProduct in openReminding)        {            //Output the name and price            lbl_NumOfSeatsLeft.Text = rowProduct["Remaining"].ToString();
        }
Within the sqlDataSource the sql code is as follows:SELECT [refNumber], [refRemaining] FROM [refFlights] WHERE ([refNumber] = @Number)
So at the moment my problems is being able to edit and update data to the same SELECTed data.Thank you for any help that you might have...
SynDrome

View 8 Replies View Related

Using SqlDatASource Programmatically - Output Parameters

May 13, 2006

I am using SqlDataSource programmatically in my data access layer - mainly for convenience but it does generally work fine with no obvious performance issues.
The problem I have is with getting back an output parameter. I have an insert-type stored procedure (in Sql Server 2005) operating on a table with an identity column as the primary key:
ALTER PROCEDURE [dbo].[InsertAlbum](@ArtistID int, @Title nvarchar(70), @NewID int OUTPUT)ASDECLARE @err intINSERT INTO dbo.ALBUMS (ARTISTID, TITLE)VALUES (@ArtistID, @Title)SELECT @err = @@error IF @err <> 0 RETURN @errSET @NewID = SCOPE_IDENTITY()
This works fine when run from Sql Server Management Studio and @NewID has the correct value.
My data access code is roughly as follows:
dsrc = New SqlDataSource()dsrc.ConnectionString = ConnectionStringdsrc.InsertCommand = "InsertAlbum"dsrc.InsertCommandType = SqlDataSourceCommandType.StoredProcedureDim parms As ParameterCollection = dsrc.InsertParametersDim newid As IntegerAddParameter(parms, "ArtistID", TypeCode.Int32, ParameterDirection.Input, 0, album.ArtistID)AddParameter(parms, "Title", TypeCode.String, ParameterDirection.Input, 0, album.Title)Dim p As New Parameter("NewID", TypeCode.Int32)p.Direction = ParameterDirection.Outputparms.Add(p)Try   Dim rv As Integer = dsrc.Insert()   newid = parms("NewID")   Return newidCatch ex As Exception   Return -1End Try
The row is inserted into the database, but however I try to define and add the NewID parameter it never has a value.
Has anyone tried to do this and can tell me what I am doing wrong?
Jon
 

View 8 Replies View Related

Programmatically Setting UpdateParameters For A SQLDataSource Control

Sep 8, 2006

I need to provide defaults and sometimes overrides for items in SQLDataSource's UpdateParameters. I am attempting to do this in a FormView's ItemUpdating and ItemInserting events as follows: //========================================================================
// FormView1_ItemUpdating:
//========================================================================
protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e) {
// not sure if this is the bets place to put this or not?
dsDataSource.UpdateParameters["UpdatedTS"].DefaultValue = DateTime.Now.ToString();
dsDataSource.UpdateParameters["UpdatedUserID"].DefaultValue = ((csi.UserInfo)Session["UserInfo"]).QuotaUserID;
}
 In the example above I am attempting to set new values for the parameters which will replace the existing values. I have found that using the DefaultValue property works ONLY if there is no current value for the parameter.  Otherwise the values I specify are ingnored.The parameters of an ObjectDataSource provide a Value property but SQLDataSource parameters do not.How can I provide an override value without needing to place the value in the visible bound form element???If you can answer this you will be the FIRST person ever to answer one of my questions here!!!Thanks,Tony 

View 2 Replies View Related

How Do I Programmatically Inert Data Using A SqlDataSource Control?

May 19, 2007

I just want to insert a record into a table using a SqlDataSource control.  But I'm having a hard time finding examples that don't use data bound controlsI have this so far (I deleted the parts not related to the insert):<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:UserPolls %>"    InsertCommand="INSERT INTO [PollAnswers] ([PollId], [AnswerText], [AnswerCount]) VALUES (@PollId, @AnswerText, @AnswerCount)"    <InsertParameters>        <asp:Parameter Name="PollId" Type="Int32" />        <asp:Parameter Name="AnswerText" Type="String" />        <asp:Parameter Name="AnswerCount" Type="Int32" />    </InsertParameters> </asp:SqlDataSource> This is the data source for a gridview control I have on the page.  I could set up an SqlDataSource for this alone if I need to, but i don't know if it would help.  From what I could find, in the code behind I should haveSqlDataSource2.Insert()and SqlDataSource2  will grab the parameters and insert the record.  The problem is I need to set the Pollid (from a session variable) and AnswerText (from a text box) at run time.  Can I do this?Diane 

View 3 Replies View Related

SQLDataSource Provide Select Parameter Value Programmatically

Sep 9, 2007

Hey All for some reason I can not get this right and/or find what I am looking for.
I have an SQLDataSource with a PartID set as the filtered value in the Datasource Query.
I am trying to use code beside to set the value and I am failing...lol...
Here is my attempt at it,
SqlDataSource1.SelectParameters("PartID") = txtPartID.Text
Any help would be great!

View 2 Replies View Related

Accessing Data From A Programmatically Created SqlDataSource

Nov 3, 2007

Hi
I think I've programmatically created a SqlDataSource - which is what I want to do; but I can't seem to access details from the source - row 1, column 1, for example????
If Not Page.IsPostBack Then
'Start by determining the connection string valueDim connString As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
'Create a SqlConnection instanceUsing connString
'Specify the SQL query
Const sql As String = "SELECT eventID FROM viewEvents WHERE eventID=17"
'Create a SqlCommand instanceDim myCommand As New Data.SqlClient.SqlCommand(sql, connString)
'Get back a DataSetDim myDataSet As New Data.DataSet
'Create a SqlDataAdapter instanceDim myAdapter As New Data.SqlClient.SqlDataAdapter(myCommand)
myAdapter.Fill(myDataSet)Label1.Text = myAdapter.Tables.Rows(0).Item("eventID").ToString() -??????????????
'Close the connection
connString.Close()
End Using
End IfThanks for any helpRichard
 

View 1 Replies View Related

Programmatically Getting The Field Values Form An Sqldatasource Control

Oct 10, 2006

Im ripping my hair out here.I need to access the field in a datasource control of use in non presentation layer code based actions.I know the I can use a code base connection and query but I dont see why i need to make two trips the the DB when the info is already available.The datasource is attached to a details view control and the details view control is nested in a loginview controlI've tried defining but all I can get in the header name of the field but not the dataitem, the dataitem causes an error  help please jim

View 4 Replies View Related

Programmatically Accessing An SQLDataSource With A SELECT COUNT(*) Query.

Jun 20, 2007

I've found example code of accessing an SQLDataSource and even have it working in my own code - an example would be  Dim datastuff As DataView = CType(srcSoftwareSelected.Select(DataSourceSelectArguments.Empty), DataView)  Dim row As DataRow = datastuff.Table.Rows(0)   Dim installtype As Integer = row("InstallMethod")  Dim install As String = row("Install").ToString  Dim notes As String = row("Notes").ToString The above only works on a single row, of course. If I needed more, I know I can loop it.The query in srcSoftwareSelected is something like "SELECT InstallMethod, Install, Notes FROM Software"My problem lies in trying to access the data in a simliar way when I'm using a SELECT COUNT query. Dim datastuff As DataView = CType(srcSoftwareUsage.Select(DataSourceSelectArguments.Empty), DataView) Dim row As DataRow = datastuff.Table.Rows(0) Dim count As Integer = row("rowcnt") The query here is "SELECT COUNT(*) as rowcnt FROM Software"The variable count is 1 every time I query this, no matter what the actual count is. I know I've got to be accessing the incorrect data member in the 2nd query because a gridview tied to srcSoftwareUsage (the SQLDataSource) always displays the correct value. Where am I going wrong here?  

View 6 Replies View Related

SqlDataSource - Need To Refresh Grid When Data Updated Programmatically

Nov 27, 2007

I am sending a GUID to a form via the query string.  If it exists I use helper functions to load most of the form text boxes.  However, if it does not then a blank form is presented and the GUID is stored in a hidden field. 
Regardless, I use this hidden field to populate a grid that is attached to a sqldatasource.
If I then add new datarows to the backend database programmatically, I cannot 'requery' the datasource to include those row upon a postback.  I cannot seem to find a simple way to force the sqldatasource to rerun the query.
Can anyone help.

View 2 Replies View Related

Programmatically Loop Through Sqldatasource - Which Event To Place It In...to Get The Right Order....

Mar 7, 2008

Hello,  I want to loop through the first 10 records that are showing in a gridview with several pages that is populated by a sqldatasource.  I can loop through the sqldatasource and get the list of values, but I'm doing something wrong because the 10 records it prints out are not the same 10 records the user sees in the gridview...They can click a search button which changes the sort, and they can click on the column headings to change the sort order.
Where's the best place to put the looping code?  I need the result to be the same as what the users sees. 
  1        Protected Sub GridView1_Sorted(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.Sorted2            Dim i As Integer = -13            Dim sTest As String = ""4            Dim vwExpensiveItems As Data.DataView = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), Data.DataView)5    6            'Loop through each record7            i = -18            For Each rowProduct As Data.DataRowView In vwExpensiveItems9                i = i + 110               'Output the name and price11               If i > 9 Then12                   Exit For13               End If14               sTest = rowProduct("employeeid")15               Response.Write("RowSorting " & i.ToString & " [" & sTest & "]<br>")16           Next17       End Sub18    

View 3 Replies View Related

DeleteCommand And UpdateCommand

Aug 1, 2006

I have added a gridview and under its properties i have changed AutoGenerateDeleteButton and AutoGenerateEditButton to true.
The problem is... when I try and delete a record, I get this error: Deleting is not supported by data source 'SqlDataSource1' unless DeleteCommand is specified
If I try and update.. i get the error: Updating is not supported by data source 'SqlDataSource1' unless UpdateCommand is specified.
Can someone please help me out... maybe with some code... or a link to a tutorial..
Thanks
Canning

View 18 Replies View Related

Have A Problem With UpdateCommand

Dec 28, 2006

Hello everyone,
 I am a bit new to ASP .Net so forgive me, if I dont understand something right off.
I am writing a page that gets code from the SQL database and puts it into a GridView. To get the information I am using SqlDataSource. I cant post an error message because I am running this off remote server but though testing I figure that it crashes when I add
Analysis = @Analysis
line into the UpdateCommand. First I thought that maybe my parameters were not read correcty but when I tried something like
Analysis  = 6
it worked. Then I tried to replace CQNo=@CQNo with
CQNo = @Analysis
and it also worked.
 I am very much puzzed at this. In SQL database CQNo is varchar, WorkDate is DateTime and Analysis is Money type.
 Can someone please help, I am out of ideas. Thanks!
<asp:SqlDataSource ID="myEfforts" runat="server"
SelectCommand="SELECT SNo, CQNo, WorkDate, Analysis, Design, Coding, Testing, DesRev, CodeRev, PeerRev, SysTest, PostInstall, Others, TotEff FROM Effort WHERE EmpId = @EmpId ORDER BY WorkDate DESC"
DeleteCommand="DELETE FROM Effort WHERE SNo=@SNo"
UpdateCommand="UPDATE Effort SET CQNo = @CQNo, WorkDate=@WorkDate Analysis=@Analysis WHERE SNo=@SNo">
<SelectParameters>
<asp:SessionParameter DefaultValue="" Name="EmpId" SessionField="PR_EmpIDVal" Type="String" />
</SelectParameters>

View 6 Replies View Related

Updatecommand Not Working With SqlDataAdapter

Aug 14, 2007

I know there are loads of posts on this, but this just will not update. I have tried various forms of the code all to no avail.  And now I'm ready to throw my PC out the window........
 What am I doing wrong? 
cheers Mike
Dim da As SqlDataAdapterDim dSetOrp As DataSet
oCn = New SqlConnection(db.m_ConnectionString)
oCn.Open()da = New SqlDataAdapter("Select * from contact WHERE conid = " & lngConId, oCn)
dSetOrp = New DataSet
da.Fill(dSetOrp, "locTable")  ' Fill the DataSet.
dSetOrp.Tables(0).Rows(0)("ConSttDate") = dtEffDateDim myBuilder As SqlCommandBuilder = New SqlCommandBuilder(da)
myBuilder.GetUpdateCommand()
da.UpdateCommand = myBuilder.GetUpdateCommand()
 lRows = da.Update(dSetOrp, "locTable")

View 2 Replies View Related

How To Update Multiple Tables With Updatecommand

Jun 5, 2007

 hi all,i'm working on a formview which will update 2 tables which are linked together but..i'm getting an error of the control not being found.my code is as shown below                           <asp:SqlDataSource ID="invDetSrc" runat="server"                                                ConnectionString="<%$ ConnectionStrings:rockwellConnectionString %>"                                               ProviderName="<%$ ConnectionStrings:rockwellConnectionString.ProviderName %>"                                               SelectCommand="SELECT rockwell.logix_asset_list.Inventory_ID, rockwell.vendor.Vendor_Name, rockwell.logix_asset_list_category.Category_Name, rockwell.logix_asset_list.Total_Quantity, rockwell.logix_asset_list.Quantity_In_Stock, rockwell.logix_asset_list.Part_Number, rockwell.logix_asset_list.On_Order, rockwell.logix_asset_list.ImageUrl, rockwell.logix_asset_list.DrawingUrl, rockwell.logix_asset_list.Description FROM rockwell.logix_asset_list, rockwell.logix_asset_list_category, rockwell.vendor WHERE rockwell.logix_asset_list.Logix_Asset_List_Category_ID = rockwell.logix_asset_list_category.Logix_Asset_List_Category_ID AND rockwell.logix_asset_list.Vendor_ID = rockwell.vendor.Vendor_ID AND&#13;&#10;rockwell.logix_asset_list.Part_Number = ?"                                               UpdateCommand="UPDATE vendor, logix_asset_list                                                set                                                vendor.vendor_name= @Vendor_Name,                                                logix_asset_list.Total_Quantity=@Total_Quantity,                                               logix_asset_list.Quantity_In_Stock=@Quantity_In_Stock,                                               logix_asset_list.Part_Number=@Part_Number,                                               logix_asset_list.On_Order=@On_Order,                                               logix_asset_list.Description=@Description                                               WHERE                                               logix_asset_list.Vendor_ID = vendor.Vendor_ID                                               and logix_asset_list.Inventory_ID = @Inventory_ID" >                               <SelectParameters>                                   <asp:ControlParameter ControlID="rstGrid" Name="?" PropertyName="SelectedValue" />                               </SelectParameters>                               <UpdateParameters>                               <asp:ControlParameter Type="Int32" ControlID="Total_Quantity" ConvertEmptyStringToNull="true" Name="@Total_Quantity"/>                               <asp:ControlParameter Type="string" ControlID="Vendor_Name" ConvertEmptyStringToNull="true" Name="@Vendor_Name"/>                               <asp:ControlParameter Type="Int32" ControlID="Quantity_In_Stock" ConvertEmptyStringToNull="true" Name="@Quantity_In_Stock"/>                               <asp:ControlParameter Type="string" ControlID="Part_Number" ConvertEmptyStringToNull="true" Name="@Part_Number"/>                               <asp:ControlParameter Type="string" ControlID="On_Order" ConvertEmptyStringToNull="true" Name="@On_Order"/>                               <asp:ControlParameter Type="string" ControlID="Description" ConvertEmptyStringToNull="true" Name="@Description"/>                               <asp:ControlParameter Type="Int32" ControlID="Inventory_ID" ConvertEmptyStringToNull="true" Name="@Inventory_ID"/>                               </UpdateParameters>                            </asp:SqlDataSource> <asp:FormView ID="FormView1" runat="server" BackColor="White" BorderColor="#DEDFDE"                                BorderStyle="None" BorderWidth="1px" CellPadding="4" DataSourceID="invDetSrc"                                ForeColor="Black" GridLines="Vertical" DataKeyNames="Inventory_ID"> <EditItemTemplate>                                    <table border="0" cellpadding="3" cellspacing="3" style="background-color: white; color: black;">                                        <tr>                                            <td colspan="2">                                                <asp:Image ID="Image1" runat="server" Height="150px" ImageUrl='<%# "~/Image/photo/Logix%20Asset/"+Eval("Category_Name")+"/"+Eval("ImageUrl") %>'                                                    Width="150px" />                                                <br />                                                <asp:HyperLink ID="drawingLink" runat="server" NavigateUrl='<%# "~/Image/drawing/Logix%20Asset/"+Eval("Category_Name")+"/"+Eval("DrawingUrl") %>'                                                    Target="_blank" Text="View Drawing" ForeColor="Blue"></asp:HyperLink>                                            </td>                                            <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Bind("Inventory_ID") %>' />                                        </tr>                                        <tr>                                            <td style="color: black">                                                Part Number:</td>                                            <td>                                                <asp:TextBox ID="Part_Number" runat="server" Text='<%# Bind("Part_Number")%>'></asp:TextBox>                                                </td>                                        </tr>                                        <tr>                                            <td>                                                <strong style="color: black">Vendor:</strong></td>                                            <td>                                                <asp:TextBox ID="Vendor_Name" runat="server" Text='<%# Bind("Vendor_Name")%>'></asp:TextBox>                                                </td>                                        </tr>                                        <tr>                                            <td style="color: black">                                                <strong>Total Quantity:</strong></td>                                            <td>                                                <asp:TextBox ID="Total_Quantity" runat="server" Text='<%# Bind("Total_Quantity")%>'></asp:TextBox>                                                </td>                                        </tr>                                        <tr>                                            <td style="color: black">                                                <strong>Quantity In Stock:</strong></td>                                            <td>                                                <asp:TextBox ID="Quantity_In_Stock" runat="server" Text='<%# Bind("Quantity_In_Stock")%>'></asp:TextBox>                                         </td>                                        </tr>                                        <tr>                                            <td style="color: black">                                                <strong>Quantity on Order:</strong></td>                                            <td>                                                <asp:TextBox ID="On_Order" runat="server" Text='<%# Bind("On_Order")%>'></asp:TextBox>                                            </td>                                        </tr>                                        <tr>                                            <td style="color: black; height: 44px;">                                                <strong>Description:</strong></td>                                            <td style="height: 44px">                                            <asp:TextBox ID="Description" runat="server" Text='<%# Bind("Description")%>' Height="53px" TextMode="MultiLine" Width="150px"></asp:TextBox></td>                                        </tr>                                        <tr>                                            <td>                                                <asp:Button ID="EditBtn" runat="server"                                                    Text="Submit Changes" Width="106px" CommandName="Update" /></td>                                            <td>                                                &nbsp;<asp:Button ID="Cancel" runat="server" Text="Cancel" CommandName="cancel" /></td>                                        </tr>                                    </table>                                </EditItemTemplate>                            </asp:FormView>any help would be much appreciated!   

View 1 Replies View Related

Manipulating A SqlDatSource UpdateCommand In Code-behind

Jul 20, 2007

We've got an employee database that I'm modifying to include two photos of each employee, a small thumbnail image and a full-size image.  The HR department maintenance page contains a listbox of employee names, which, when clicked, populates a detailsview control.To get the images to display and be updatable, I've had to structure the following SqlDatasource and DetailsView:
1    <asp:DetailsView ID="dvEmp" runat="server"2      AutoGenerateRows="false"3      DataSourceID="dsEmpView"4      DataKeyNames="empID">5    <Fields>6    <asp:CommandField ShowEditButton="true" ShowCancelButton="true" ShowInsertButton="true" />7    <asp:BoundField HeaderText="Name (Last, First)" DataField="empname" />8    <asp:TemplateField HeaderText="Thumbnail photo">9    <ItemTemplate>10   <asp:Image ID="imgThumbnail" runat="server" ImageUrl='<%# formatThumbURL(DataBinder.Eval(Container.DataItem,"empID")) %>' />11   </ItemTemplate>12   <EditItemTemplate>13   <asp:Image ID="imgThumbHidden" runat="server" ImageUrl='<%# Bind("thumbURL") %>' Visible="false" />14   <asp:FileUpload ID="upldThumbnail" runat="server" />15   </EditItemTemplate>16   </asp:TemplateField>17   <asp:TemplateField HeaderText="Full Photo">18   <ItemTemplate>19   <asp:Image ID="imgPhoto" runat="server" ImageUrl='<%# formatImageURL(DataBinder.Eval(Container.DataItem,"empID")) %>'  />20   </ItemTemplate>21   <EditItemTemplate>22   <asp:Image ID="imgPhotoHidden" runat="server" ImageUrl='<%# Bind("photoURL") %>' Visible="false" />23   <asp:FileUpload ID="upldPhoto" runat="server" />24   </EditItemTemplate>25   </asp:TemplateField>26   </Fields>27   </asp:DetailsView>28   29   <asp:SqlDataSource ID="dsEmpView"30     runat="server"31     ConnectionString="<%$ ConnectionStrings:eSignInConnectionString %>"32     OnInserting="dsEmpView_Inserting"33     OnUpdating="dsEmpView_Updating"34     SelectCommand="SELECT empID, empname, photoURL, thumbURL FROM employees where (empID = @empID)"35     InsertCommand="INSERT INTO employees (empname, photoURL, thumbURL) values(@empname, @photoURL, @thumbURL)"36     UpdateCommand="UPDATE employees SET empname=@empname, photoURL=@photoURL, thumbURL=@thumbURL WHERE (empID = @empID)">37     <SelectParameters>38       <asp:ControlParameter ControlID="lbxEmps" Name="empID" PropertyName="SelectedValue" Type="Int16" />39     </SelectParameters>40   </asp:SqlDataSource>41   42   -----43   44   Protected Sub dsEmpView_Updating(ByVal sender As Object, ByVal e As SqlDataSourceCommandEventArgs)45     Dim bAbort As Boolean = False46     Dim bThumb(), bPhoto() As Byte47     If e.Command.Parameters("@ename").Value.trim = "" Then bAbort = True48     Dim imgT As FileUpload = CType(dvEmp.FindControl("upldThumbnail"), FileUpload)49     If imgT.HasFile Then50       Using reader As BinaryReader = New BinaryReader(imgT.PostedFile.InputStream)51         bThumb = reader.ReadBytes(imgT.PostedFile.ContentLength)52         e.Command.Parameters("@thumbURL").Value = bThumb53       End Using54     End If55     Dim imgP As FileUpload = CType(dvEmp.FindControl("upldPhoto"), FileUpload)56     If imgP.HasFile Then57       Using reader As BinaryReader = New BinaryReader(imgP.PostedFile.InputStream)58         bPhoto = reader.ReadBytes(imgP.PostedFile.ContentLength)59         e.Command.Parameters("@photoURL").Value = bPhoto60       End Using61     End If62     e.Cancel = bAbort63   End SubIf the user updates both images at the same time by populating their respective FileUpload boxes, everything works as advertized.  But if the user only updates one image (or neither image), things break. If they upload, say, just the full-size photo during an update, then it gives the error "System.Data.SqlClient.SqlException: Operand type clash: nvarchar is incompatible with image".I think this error occurs because the update command is trying to set the parameter "thumbURL" without having any actual data to set.  But since I really don't want this image updated with nothing, thereby erasingthe photo already in the database, I'd rather remove this parameter from the update string.So, let's remove the parameter that updates that image by adding the following code just after the "End Using" lines: Else
Dim p As SqlClient.SqlParameter = New SqlClient.SqlParameter("@thumbURL", SqlDbType.Image)
e.Command.Parameters.Remove(p)
(Similar code goes into the code block that handles the photo upload)Running the same update without an image in the thumb fileupload box, I now get this error: "System.ArgumentException: Attempted to remove an SqlParameter that is not contained by this SqlParameterCollection."Huh?  It's not there?  Okay, so lets work it from the other end: let's remove all references to the thumbURL and photoURL from the dsEmpView datasource.  We'll make its UpdateCommand = "UPDATE employees SET empname=@empname WHERE (empID = @empID)", and put code in the dsEmpView_Updating sub that adds the correct parameter to the update command, but only if the fileupload box has something in it.  Therefore: If imgT.HasFile Then
Using reader As BinaryReader = New BinaryReader(imgT.PostedFile.InputStream)
bThumb = reader.ReadBytes(imgT.PostedFile.ContentLength)
e.Command.Parameters.Add(New SqlClient.SqlParameter("@thumbURL", SqlDbType.Image, imgT.PostedFile.ContentLength))
e.Command.Parameters("@thumbURL").Value = bThumb
End Using
End If
(Similar code goes into the code block that handles the photo upload)But reversing the angle of attack only reverses the error. Uploading only the photo and not the thumb image results in: "System.Data.SqlClient.SqlException: The variable name '@photoURL' has already been declared. Variable names must be unique within a query batch or stored procedure."So now it's telling me the parameter IS there, even though I just removed it.ARRRGH!What am I doing wrong, and more importantly, how can I fix it?Thanks in advance. 

View 5 Replies View Related

Dynamic SQL Generation For The UpdateCommand Is Not Supported

Nov 7, 2007

Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.

I am getting the above error if i try to create a update command through a Command builder in .net cf on a SQLCE 3.0 database

The Select query I used for creating the update command is 'SELECT * FROM Users'


I populated a datatable with the above query through a DataAdapter, to check for the primary key and the primary key was available in the table. But still the CB could not able to create an Update Command for that query,

The Primary Key column that I use is of type GUID

Then when try to do the above job using a Typed DataSet with TableAdapters , then it throws the following error

'Update requires a valid UpdateCommand when passed DataRow Collection with modified rows'

can any one please tell me a way to fix this ,

Thanks and Regards
Varadan

View 6 Replies View Related

SQL Construct

Dec 19, 2006

Hi all,

I had a question regarding SQL construct.

I had a table named "info" and I would like to show Lot_Id as distinct. Besides that , I would also like to show wafer_id and wafer_starttime. May I know how to construct this using select statement?

Thanks

View 1 Replies View Related

Can Someone Help Me Construct A SQL Command....

Oct 18, 2005

My head hurts...it might be an easy one for many people, but cant seem to figure a way to do it.Ok, I have a table with a field called Ad_Price.  This field is a nvarchar one, theres many different value in it, all of them corresponding to a price.  Now, what I want to do is only get the row that are not written in a good price format (like123$  is wrong, but 123.00 is good, but only value following this exemple)For exemple, if I have all these value145.876785.34654$45 to negociate1bvcaa0.01876.556the value I want to have are:654$45 to negociate1bvcaa876.556because they dont follow the format I wantso im not sure if my explication was clear enough..all in all what I want to complete is the WHERE part of my SQL instruction...what should I put in:SELECT *FROM AdsWHERE ???????thansk for taking the time to read this

View 2 Replies View Related

CASE SQL Construct

Sep 27, 2005

I am using the following code to construct an SQL 7.0 View Column

"CASE WHEN [DailyHours] > SUM([TransAmt]) THEN 0 ELSE 1 END"

and it works great!!

However, when I try the same line in SQL 2000, I get the message "The query designer does not support the case SQL construct"

The help screen is no help as all it says is "the syntax you entered is valid but is not supported visually by Query Designer. Be sure the verify your syntax before saving."

It will not let me save, so I'm not sure what to do from here now????

View 8 Replies View Related

Construct Variable Name?

Mar 16, 2006

Can you contruct a variable name from another variable? For example, I want the following to PRINT 10


DECLARE @var1 INT
DECLARE @var2 INT

SET @var1 = 10
SET @var2 = 20

PRINT '@var' + '1'


This prints the variable name, not the contents of the var. I tried to parse it with square brackets, but no luck.

Thanks,
Carl

View 6 Replies View Related

Gridview - Updating Is Not Supported By Data Source 'SqlDataSourceGridView' Unless UpdateCommand Is Specified

May 13, 2008

 Hi all,I have a gridview that bound to a SqlDataSource called SqlDataSourceGridView. I have enabled Edit in my GridView, but I do all the updating in code behind with stored procedure (using onRowUpdating). Now each time when I click "Update", the update went through and all the data got updated, but I received this error: Updating is not supported by data source 'SqlDataSourceGridView' unless UpdateCommand is specified.



Description: An
unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the
error and where it originated in the code.

Exception Details: System.NotSupportedException:
Updating is not supported by data source 'SqlDataSourceGridView' unless
UpdateCommand is specified. What do I need to do to fix this problem?Thanks a lot. 

View 6 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved