Need Help With Updating A Gridview From Code-behind

May 8, 2007

Hi,

I've got a gridview that displays some (but not all) columns from a sql database table. One of the columns that is NOT displayed is the table's primary key column. I'm putting together this row updating sub based on an article I found on the 'Net. Here's the code I've added for the GridView's edit routine (based on the article):Protected Sub gvPersonnelType_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gvPersonnelType.RowEditing
gvPersonnelType.EditIndex = e.NewEditIndex
gvPersonnelTypeBindData()
End Sub

Protected Sub gvPersonnelType_RowCancellingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
gvPersonnelType.EditIndex = -1
gvPersonnelTypeBindData()
End Sub

Protected Sub gvPersonnelType_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
'Dim PersonnelTypeID As Integer'This is not displayed in the gridview, but is the primary key in the database
Dim LaborForceTypeID As Integer
Dim DefaultPayRate, DefaultPieceRate, Rebill As Decimal'These are money datatype in the database
Dim DefaultAdminCostPercent, MarkUp As Double 'These are float datatype in the database'Don't know if the following lines properly "capture" the values in the textboxes
LaborForceTypeID = Integer.Parse(gvPersonnelType.Rows(e.RowIndex).Cells(0).Text)
DefaultPayRate = CType(gvPersonnelType.Rows(e.RowIndex).Cells(1).Controls(0), TextBox).Text
DefaultPieceRate = CType(gvPersonnelType.Rows(e.RowIndex).Cells(2).Controls(0), TextBox).Text
DefaultAdminCostPercent = CType(gvPersonnelType.Rows(e.RowIndex).Cells(3).Controls(0), TextBox).Text
Rebill = CType(gvPersonnelType.Rows(e.RowIndex).Cells(4).Controls(0), TextBox).Text
MarkUp = CType(gvPersonnelType.Rows(e.RowIndex).Cells(5).Controls(0), TextBox).Text

Dim gvSqlConn = New SqlConnection("DATABASECONNECTION")

gvSqlConn.open()
Dim UpdatePersonnelTypeCmd As New SqlCommand("UPDATE rsrc_PersonnelType SET LaborForceTypeID = @LaborForceTypeID, " & _
"DefaultPayRate = @DefaultPayRate, DefaultPieceRate = @DefaultPieceRate, " & _
"DefaultAdminCostPercent = @DefaultAdminCostPercent, Rebill = @Rebill, Markup = @Markup", gvSqlConn)

'Sql doesn't know what row to update: NEED WHERE STATEMENT!!!

UpdatePersonnelTypeCmd.Parameters.Add(New SqlParameter("@LaborForceTypeID", LaborForceTypeID))
UpdatePersonnelTypeCmd.Parameters.Add(New SqlParameter("@DefaultPayRate", DefaultPayRate))
UpdatePersonnelTypeCmd.Parameters.Add(New SqlParameter("@DefaultPieceRate", DefaultPieceRate))
UpdatePersonnelTypeCmd.Parameters.Add(New SqlParameter("@DefaultAdminCostPercent", DefaultAdminCostPercent))
UpdatePersonnelTypeCmd.Parameters.Add(New SqlParameter("@Rebill", Rebill))
UpdatePersonnelTypeCmd.Parameters.Add(New SqlParameter("@Markup", MarkUp))

UpdatePersonnelTypeCmd.ExecuteNonQuery()
gvSqlConn.close()

gvPersonnelType.EditIndex = -1
gvPersonnelTypeBindData()

End Sub

 As you can see, I've added some notes in the RowUpdating sub. I don't understand how to use the PersonnelTypeID (the database table's primary key) for the WHERE clause to update the correct row in the database.

As for the GridView itself, it's populated from the code-behind as well (as you can see from the call to "gvPersonnelTypeBindData()") and the SELECT statement used to populate the gridview doesn't use the PersonnelTypeID column either.

I'd appreciate it if someone could point me in the right direction to get this RowUpdating sub working.

Thanks!

View 5 Replies


ADVERTISEMENT

Deleting And Updating From Gridview

Nov 10, 2007

Hi,I made a gridview, and I am trying to make it so when the user deletes a row, values in other tables update. I used the following source code:    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"        DeleteCommand="DELETE FROM [Transactions] WHERE [TransactionID] = @TransactionID AND UPDATE [items] SET Quantityavailable, numtaken VALUES Quantityavailable + 1, numtaken - 1 WHERE ([Itemid] = @Itemid) " It gives the error that Quantityavailable is not a SET type?Thanks if you can suggest a remedy! Jon 

View 2 Replies View Related

Gridview Date Field Not Updating

Jan 31, 2008

Hi - Once again I've been looking at this forever and not able to see the problem.  Have a grid table everything updates except the training date field.  That get's wiped out each time - no matter if something is in it or not.  Everything else updates correctly.
Here's the code: 
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="ds1" DataKeyNames="eventID"><Columns><asp:CommandField ButtonType="Button" ShowEditButton="True" ShowDeleteButton="True" /><asp:BoundField DataField="eventID" HeaderText="ID" SortExpression="eventID" ReadOnly="True"><HeaderStyle Font-Bold="True" Font-Names="Verdana" Font-Size="Small" /><ItemStyle Font-Names="Verdana" Font-Size="Small" /></asp:BoundField><asp:TemplateField HeaderText="Training Date" SortExpression="trainingDate"><EditItemTemplate><asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("trainingDate", "{0:M/dd/yy}") %>'></asp:TextBox></EditItemTemplate><ItemTemplate><asp:Label ID="Label1" runat="server" Text='<%# Bind("trainingDate", "{0:M/dd/yy}") %>'></asp:Label></ItemTemplate><HeaderStyle Font-Bold="True" Font-Names="Verdana" Font-Size="Small" /><ItemStyle Font-Names="Verdana" Font-Size="Small" /></asp:TemplateField>
<asp:SqlDataSource ID="ds1" runat="server" ConnectionString="<%$ ConnectionStrings:TrainingClassTrackingConnectionString %>" ProviderName="<%$ ConnectionStrings:TrainingClassTrackingConnectionString.ProviderName %>"UpdateCommand="UPDATE [trainingLog] SET  [trainingDate] = @trainingDate WHERE [eventID] = ?" >
<UpdateParameters><asp:Parameter Name="trainingDate" Type="DateTime" /></UpdateParameters>

View 2 Replies View Related

SqlDataSource Not Updating On Editing GridView

Mar 4, 2007

Hi, I'm new in ASP 2.0. I need to incorporate edit and delete capability in GridView. Using the wizard, i've generated this code. When I delete a row, it gets deleted but update does not work. I've tried several ways. I got no error or exception. But row is not updated. I've checked database, and I think the update query is not executing at all. Please let me know, what I'm doing wrong? Here is the source code for reference. I'm using Visual Studio 2005 with SQL server 2005 Express Edition. Regards

==========================================================
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="QuoteItemID" DataSourceID="SqlDataSource1"> <Columns> <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" CausesValidation="False" /> <asp:BoundField DataField="QuoteItemID" HeaderText="QuoteItemID" InsertVisible="False" ReadOnly="True" SortExpression="QuoteItemID" /> <asp:BoundField DataField="QuoteID" HeaderText="QuoteID" SortExpression="QuoteID" /> <asp:BoundField DataField="ChargeCodeID" HeaderText="ChargeCodeID" SortExpression="ChargeCodeID" /> <asp:BoundField DataField="RateItemAmount" HeaderText="RateItemAmount" SortExpression="RateItemAmount" /> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ratesdb %>" DeleteCommand="DELETE FROM [Quote_item] WHERE [QuoteItemID] = @QuoteItemID" InsertCommand="INSERT INTO [Quote_item] ([QuoteID], [ChargeCodeID], [RateItemAmount]) VALUES (@QuoteID, @ChargeCodeID, @RateItemAmount)" SelectCommand="SELECT * FROM [Quote_item]" UpdateCommand="UPDATE [Quote_item] SET [QuoteID] = @QuoteID, [ChargeCodeID] = @ChargeCodeID, [RateItemAmount] = @RateItemAmount WHERE [QuoteItemID] = @QuoteItemID" ConflictDetection="CompareAllValues"> <DeleteParameters> <asp:Parameter Name="QuoteItemID" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="QuoteID" Type="Int32" /> <asp:Parameter Name="ChargeCodeID" Type="Int32" /> <asp:Parameter Name="RateItemAmount" Type="Decimal" /> <asp:Parameter Name="QuoteItemID" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="QuoteID" Type="Int32" /> <asp:Parameter Name="ChargeCodeID" Type="Int32" /> <asp:Parameter Name="RateItemAmount" Type="Decimal" /> </InsertParameters> </asp:SqlDataSource>

View 6 Replies View Related

Filling Gridview From Code

Aug 2, 2007

 hello, i'd need a little help with filling GridViewsi browsed over like 10 search pages, but couldnt find any which would solve my problem.so in my ajax project i made a testing page pulled a gridview (GridView1) on it with a fhew buttons and textboxes.i need to fill the gv from code so my websie.asp.cs looks like this 1 protected void Page_Load(object sender, EventArgs e)2 {3 4 5 string connstr = "Data Source=.;database=teszt;user id=user;password=pass";6 SqlConnection conn = new SqlConnection(connstr);7 SqlCommand comm = new SqlCommand("select * from users", conn);8 conn.Open();9 SqlDataReader reader;10 reader = comm.ExecuteReader();11 if (reader.HasRows)12 {13 GridView1.DataSource = reader;14 GridView1.DataBind();15 }16 reader.Close();17 conn.Close();18 comm.Dispose();19 } so i load the page and there's no gridview on the page at all, nor an error msg, the connection and the database/table is fine.any suggestions on what am i doing wrong? and i also like to know if there would be any problem with using this on a tabcontrol/tabthankyou  

View 3 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

Change Dynamically(via Code) The SqlDataSource For A GridView....

Mar 7, 2007

Hi,
say I have two Sqldatasources objects:SqlDataSource1 and SqlDataSource2....
Does anybody know how can I alter programmatically these two sqldatasources in a gridview?
Thanks!!!

View 3 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

Performance Comparison - Code Vs SqlDataSource, Gridview Etc Vs PlainControl

Jun 9, 2007

There are so many ways to use database in asp.net/ado.net, I'm a bit confused about their difference from the performance point of view.So apparently SqlDataSource in DataReader mode is faster than DataSet mode, at a cost of losing some bolt-on builtin functions.What about SqlDataSource in DataReader mode vs manual binding in code? Say creating a SqlDataSource ds1 and set "DataSourceID" in Gridview, vs manually creating the SqlConnection, SqlCommand, SqlDataReader objects and mannually bind the myReader object to the gridview with the Bind() method.Also Gridview is a very convenient control for many basic tasks. But for more complex scenarios it requires lots of customization and modification. Now if I do not use gridview at all and build the entire thing from scratch with basic web controls such as table and label controls, and mannually read and display everything from a DataReader object, how's the performance would be like compared to the Gridview-databind route?

View 3 Replies View Related

SQL Syntax In ASP.net Code Not Updating

Mar 3, 2008

Hi,
I am trying to build a website in C# for a university project, and am having trouble updating a table from the code (at which I'm not too hot on writing).  I can manage to get the SQL syntax to work in SQL Server 2005, but when I transfer it to the Visual Web Developer page it doesn't update.  Would anyone be able to kindly point out where I am going wrong?  My code (apologies for the amount) is;protected void CalculateEmissionsAndTotal()
{
//Create the ConnectionSqlConnection sqlConn =
new SqlConnection("server=Acer-Laptop\SQLEXPRESS; database=NeuCar; Trusted_Connection=true");
//Open the connection
sqlConn.Open();
//Create the Command, passing in the SQL statement and the ConnectionString queryString = "DECLARE @Today DATETIME SELECT @Today = Current_Timestamp Declare @TotalCharge int DECLARE @EmissionsUrban int DECLARE @EmissionsCountry int SELECT @TotalCharge = ((MemberPayment.MileageUrban * Vehicle.EmissionsPerGramUrban) * 0.05) + ((MemberPayment.MileageCountry * Vehicle.EmissionsPerGramUrban) * 0.05) FROM [NeuCar].[dbo].[MemberPayment] JOIN [NeuCar].[dbo].[Vehicle] ON MemberPayment.Registration = Vehicle.Registration JOIN [NeuCar].[dbo].[Member] ON Vehicle.UserName = Member.UserName WHERE (Member.UserName = @myUserName) AND (MemberPayment.PaymentDate >= DATEADD(dd,-(DAY(DATEADD(mm,-1,@Today))-1),DATEADD(mm,0,@Today))) SELECT @EmissionsUrban = ((MemberPayment.MileageUrban * Vehicle.EmissionsPerGramUrban) * 0.05) FROM [NeuCar].[dbo].[MemberPayment] JOIN [NeuCar].[dbo].[Vehicle] ON MemberPayment.Registration = Vehicle.Registration JOIN [NeuCar].[dbo].[Member] ON Vehicle.UserName = Member.UserName WHERE (Member.UserName = @myUserName) AND (MemberPayment.PaymentDate >= DATEADD(dd,-(DAY(DATEADD(mm,-1,@Today))-1),DATEADD(mm,0,@Today))) SELECT @EmissionsCountry = ((MemberPayment.MileageCountry * Vehicle.EmissionsPerGramCountry) * 0.05) FROM [NeuCar].[dbo].[MemberPayment] JOIN [NeuCar].[dbo].[Vehicle] ON MemberPayment.Registration = Vehicle.Registration JOIN [NeuCar].[dbo].[Member] ON Vehicle.UserName = Member.UserName WHERE (Member.UserName = @myUserName) AND (MemberPayment.PaymentDate >= DATEADD(dd,-(DAY(DATEADD(mm,-1,@Today))-1),DATEADD(mm,0,@Today))) UPDATE MemberPayment SET TotalCharge = @TotalCharge, EmissionsUrban = @EmissionsUrban, EmissionsCountry = @EmissionsCountry WHERE (Registration = @myRegistration); ";
SqlCommand cmd = new SqlCommand(queryString, sqlConn);cmd.Parameters.Add(new SqlParameter("@myUserName", Session["sUserName"]));
cmd.Parameters.Add(new SqlParameter("@myRegistration", Session["sRegistration"]));MileageLabel.Text = "*Update complete";
//Close the connection
sqlConn.Close();
}
I would be very grateful if anybody could help,
Kind regards,
Chima

View 3 Replies View Related

Updating Stored Procs From Code

Feb 14, 2006

I have an SSE system/database with a WinForms (VB.NET) application front end... i am just wondering how I can update a stored procedure in the local SSE database from my application?

This is a real big issue for us and our automated deployment.

Any help would be great!!!!!!

ward0093

View 8 Replies View Related

What Could Be The Problem With My Code? Its Not Updating The Database

Sep 19, 2006

Hi

My code that Im using is not updating the database, Im using the following stored procedure :-


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[Update_VMI_Capture]
(
@ID int,
@Weighbridge nvarchar(50),
@Volume float,
@DateTime datetime,
@Fuel_Type nvarchar(50)
)
AS
SET NOCOUNT OFF;
UPDATE VMI_Capture
SET Weighbridge = @Weighbridge, Volume = @Volume, DateTime=@DateTime, Fuel_Type=@Fuel_Type
WHERE ([ID] = @ID)


When Im running this procedure using SQL Server Management Studio it runs perfect.

The problem is when I use a little C# code to run this procedure like :-


int ID = Convert.ToInt32(Request.QueryString["ID"]);
SQLCONN get_con = new SQLCONN();
System.Data.SqlClient.SqlConnection connect = new System.Data.SqlClient.SqlConnection(get_con.RETSQLCONN());
System.Data.SqlClient.SqlCommand cmd_get_Data = new System.Data.SqlClient.SqlCommand("Update_VMI_Capture", connect);
cmd_get_Data.CommandType = System.Data.CommandType.StoredProcedure;
cmd_get_Data.Parameters.Add("@ID", System.Data.SqlDbType.Int).Value = ID;
cmd_get_Data.Parameters.Add("@Weighbridge", System.Data.SqlDbType.NVarChar, 50).Value = txtNumber.Text;
cmd_get_Data.Parameters.Add("@Volume", System.Data.SqlDbType.Float).Value = Convert.ToSingle(txtVolume.Text);
cmd_get_Data.Parameters.Add("@DateTime", System.Data.SqlDbType.DateTime).Value = Convert.ToDateTime(txtDate.Text);
cmd_get_Data.Parameters.Add("@Fuel_Type", System.Data.SqlDbType.NVarChar, 50).Value = txtFuel.Text;
connect.Open();
LabelStatus.Text = cmd_get_Data.ExecuteNonQuery().ToString();
connect.Close();


LabeStatus return 1, but when I check the table in the database there is no change and I dont understand why? am I doiing this wrong please help.

View 1 Replies View Related

Updating Sql DB. My Code Compiles, But Doesn't Update.

Sep 15, 2006

C#, Webforms, VS 2005, SQL Hi all, quick hit question.  I'm trying to update a table with an employee name and hire date.  Session variable of empID, passed from a previous page (successfully) determines which row to plop the update into. It's not working even though i compiles and makes it all the way through the code to the txtReturned.Text = "I made it" debug line...Any thoughts?    1 string szInsSql;
2
3 string sConnectionString = "Data Source=dfssql;Database=MyDB;uid=myID;pwd=myPWD";
4 SqlConnection objConn = new SqlConnection(sConnectionString);
5
6 objConn.Open();
7
8 szInsSql = "UPDATE empEmployee SET " +
9 "Name = '" + this.txtName.Text + "', " +
10 "HireDate = '" + this.txtHireDate.Text + "', " +
11 "WHERE empID = '" + Session[empID] + "'";
12
13 SqlCommand objCmd1 = new SqlCommand(szInsSql, objConn);
14 objCmd1.ExecuteNonQuery();
15
16 txtReturned.Text = "I made it";
 It's got to be a ' or a , out of place but I've looked at this code for a half hour straight, trying a variety of changes...and it still doesn't update the DB...Any help would be great.  Thank you! -Corby- 

View 3 Replies View Related

The Database Is Not Updating Any Values, I There A Problem With My Code?

Oct 6, 2006

Im trying to update the values int the database and the query is executed correctly but database is not updated and the returned message is one, I really dont know whats causing this here is my code.1 private void UpdatetheDatabase(string connection)
2 {
3 SqlConnection connect = new SqlConnection(connection);
4 SqlCommand update_customer_details = new SqlCommand("UPDATE [app_CustomerDetails] " +
5 " SET [Name]=@Name,[City]=@City, " +
6 " WHERE [ID]=@ID", connect);
7 update_customer_details.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value = txtCustomerName.Text;
8 update_customer_details.Parameters.Add("@City", SqlDbType.NVarChar, 50).Value = txtCity.Text;
9 update_customer_details.Parameters.Add("@ID", SqlDbType.Int, 4).Value = ID;
10 connect.Open();
11 int x = update_customer_details.ExecuteNonQuery();
12 connect.Close();
13 StatusLabel.Text = x.ToString();
14 }
 your help will be highly appreciated.

View 7 Replies View Related

Want Error Message To Appear When No Database Results Were Returned In GridView, Also Other GridView Issues.

Jun 12, 2008

Hi, I am seeking a hopefully easy solution to spit back an error message when a user receives no results from a SQL server db with no results. My code looks like this What is in bold is the relevant subroutine for this problem I'm having.   Partial Class collegedb_Default Inherits System.Web.UI.Page Protected Sub submit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submit.Click SqlDataSource1.SelectCommand = "SELECT * FROM [college_db] WHERE [name] like '%" & textbox1.Text & "%'" SqlDataSource1.DataBind() If (SqlDataSource1 = System.DBNull) Then no_match.Text = "Your search returned no results, try looking manually." End If End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load SqlDataSource1.SelectCommand = "SELECT * FROM [college_db] ORDER BY [name]" SqlDataSource1.DataBind() End Sub Protected Sub reset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles reset.Click SqlDataSource1.SelectCommand = "SELECT * FROM [college_db] ORDER BY [name]" SqlDataSource1.DataBind() End SubEnd Class  I'm probably doing this completely wrong, I'm a .net newb. Any help would be appreciated. Basically I have GridView spitting out info from a db upon Page Load, but i also have a search bar above that. The search function works, but when it returns nothing, I want an error message to be displayed. I have a label setup called "no_match" but I'm getting compiler errors. Also, next to the submit button, I also have another button (Protected sub reset) that I was hoping to be able to return all results back on the page, similar to if a user is just loading the page fresh. I'd think that my logic would be OK, by just repeating the source code from page_load, but that doens't work.The button just does nothing. One final question, unrelated. After I set this default.aspx page up, sorting by number on the bottom of gridview, ie. 1,2,3,4, etc, worked fine. But now that paging feature, as long with the sorting headers, don't work! I do notice on the status bar in the browser, that I receive an error that says, "error on page...and it referers to javascript:_doPostBack('GridView1, etc etc)...I have no clue why this happened. Any help would be appreciated, thanks! 

View 2 Replies View Related

Why Is This SQL UPDATE Query Not Updating When This Code Is Used Under Button.click.

Mar 20, 2008

Why is this SQL UPDATE query not updating when this code is used under button.click.

Dim ListingID As String = Request.QueryString("id").ToString
Dim sqlupdate As String = "UPDATE Listings SET PlaceName = '" & PlaceName.Text & "', Location = '" & Location.SelectedValue & "', PropertyType = '" & PropertyType.SelectedValue & "', Description = '" & Description.Text & "', Price = '" & Price.Text & "' WHERE ListingID ='" & ListingID & "'"
Dim con As New SqlConnection(ListingConnection)
Dim cmd As New SqlCommand(sqlupdate, con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()

View 12 Replies View Related

Updating Data In Database VB Code Problem, Must Declare Scalar Variable

Feb 18, 2008

I get a Must Declare Scalar Variable for CompanyName error. Please help. Thank you. datasource.ConnectionString = ConfigurationManager.ConnectionStrings("ConnString").ToString()
datasource.UpdateCommand = ("UPDATE Company SET [CompanyName] = @CompanyName), = @Email, [PhoneNumber] = @PhoneNumber, [WebsiteName] = @WebsiteName WHERE ([CompanyID] = " & Request.QueryString("CID"))datasource.UpdateParameters.Add("@CompanyName", txtName.Text)
datasource.UpdateParameters.Add("@Email", txtEmail.Text)datasource.UpdateParameters.Add("@PhoneNumber", txtPhoneNumber.Text)
datasource.UpdateParameters.Add("@WebsiteName", txtWebsite.Text)
datasource.Update()

View 4 Replies View Related

Updating A Table By Both Inserting And Updating In The Data Flow

Sep 21, 2006

I am very new to SQL Server 2005. I have created a package to load data from a flat delimited file to a database table. The initial load has worked. However, in the future, I will have flat files used to update the table. Some of the records will need to be inserted and some will need to update existing rows. I am trying to do this from SSIS. However, I am very lost as to how to do this.

Any suggestions?

View 7 Replies View Related

Help With Converting Code: VB Code In SQL Server 2000-&&>Visual Studio BI 2005

Jul 27, 2006

Hi all--I'm trying to convert a function which I inherited from a SQL Server 2000 DTS package to something usable in an SSIS package in SQL Server 2005. Given the original code here:
Function Main()
on error resume next
dim cn, i, rs, sSQL
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=sqloledb;Server=<server_name>;Database=<db_name>;User ID=<sysadmin_user>;Password=<password>"
set rs = CreateObject("ADODB.Recordset")
set rs = DTSGlobalVariables("SQLstring").value

for i = 1 to rs.RecordCount
sSQL = rs.Fields(0).value
cn.Execute sSQL, , 128 'adExecuteNoRecords option for faster execution
rs.MoveNext
Next

Main = DTSTaskExecResult_Success

End Function

This code was originally programmed in the SQL Server ActiveX Task type in a DTS package designed to take an open-ended number of SQL statements generated by another task as input, then execute each SQL statement sequentially. Upon this code's success, move on to the next step. (Of course, there was no additional documentation with this code. :-)

Based on other postings, I attempted to push this code into a Visual Studio BI 2005 Script Task with the following change:

public Sub Main()

...

Dts.TaskResult = Dts.Results.Success

End Class

I get the following error when I attempt to compile this:

Error 30209: Option Strict On requires all variable declarations to have an 'As' clause.

I am new to Visual Basic, so I'm on a learning curve here. From what I know of this script:
- The variables here violate the new Option Strict On requirement in VS 2005 to declare what type of object your variable is supposed to use.

- I need to explicitly declare each object, unless I turn off the Option Strict On (which didn't seem recommended, based on what I read).

Given this statement:

dim cn, i, rs, sSQL

I'm looking at "i" as type Integer; rs and sSQL are open-ended arrays, but can't quite figure out how to read the code here:

Set cn = CreateObject("ADODB.Connection")

cn.Open "Provider=sqloledb;Server=<server_name>;Database=<db_name>;User ID=<sysadmin_user>;Password=<password>"

set rs = CreateObject("ADODB.Recordset")

This code seems to create an instance of a COM component, then pass provider information and create the recordset being passed in by the previous task, but am not sure whether this syntax is correct for VS 2005 or what data type declaration to make here. Any ideas/help on how to rewrite this code would be greatly appreciated!

View 7 Replies View Related

How To Show Description In Report Instead Of Code (Desc For Code Is In Master Table)

Mar 28, 2007

Dear Friends,



I am having 2 Tables.

Table 1: AddressBook
Fields --> User Name, Address, CountryCode



Table 2: Country
Fields --> Country Code, Country Name


Step 1 : I have created a Cube with these two tables using SSAS.



Step 2 : I have created a report in SSRS showing Address list.

The Column in the report are User Name, Address, Country Name



But I have no idea, how to convert this Country Code to Country name.

I am generating the report using the Layout tab. ( Data | Layout | Preview ) Report1.rdl [Design]



Anyone help me to solve this issue. Because, in our project most of the transaction tables have Code and Code description in master table. I need to convert all code into corresponding description in all my reports.




Thanks in advance.





Regards
Ramakrishnan
Singapore
28 March 2007

View 4 Replies View Related

Many Lines Of Code In Stored Procedure && Code Behind

Feb 24, 2008

Hello,
I'm using ASP.Net to update a table which include a lot of fields may be around 30 fields, I used stored procedure to update these fields. Unfortunatily I had to use a FormView to handle some TextBoxes and RadioButtonLists which are about 30 web controls.
I 've built and tested my stored procedure, and it worked successfully thru the SQL Builder.The problem I faced that I have to define the variable in the stored procedure and define it again the code behind againALTER PROCEDURE dbo.UpdateItems
(
@eName nvarchar, @ePRN nvarchar, @cID nvarchar, @eCC nvarchar,@sDate nvarchar,@eLOC nvarchar, @eTEL nvarchar, @ePhone nvarchar,
@eMobile nvarchar, @q1 bit, @inMDDmn nvarchar, @inMDDyr nvarchar, @inMDDRetIns nvarchar,
@outMDDmn nvarchar, @outMDDyr nvarchar, @outMDDRetIns nvarchar, @insNo nvarchar,@q2 bit, @qper2 nvarchar, @qplc2 nvarchar, @q3 bit, @qper3 nvarchar, @qplc3 nvarchar,
@q4 bit, @qper4 nvarchar, @pic1 nvarchar, @pic2 nvarchar, @pic3 nvarchar, @esigdt nvarchar, @CCHName nvarchar, @CCHTitle nvarchar, @CCHsigdt nvarchar, @username nvarchar,
@levent nvarchar, @eventdate nvarchar, @eventtime nvarchar
)
AS
UPDATE iTrnsSET eName = @eName, cID = @cID, eCC = @eCC, sDate = @sDate, eLOC = @eLOC, eTel = @eTEL, ePhone = @ePhone, eMobile = @eMobile,
q1 = @q1, inMDDmn = @inMDDmn, inMDDyr = @inMDDyr, inMDDRetIns = @inMDDRetIns, outMDDmn = @outMDDmn,
outMDDyr = @outMDDyr, outMDDRetIns = @outMDDRetIns, insNo = @insNo, q2 = @q2, qper2 = @qper2, qplc2 = @qplc2, q3 = @q3, qper3 = @qper3,
qplc3 = @qplc3, q4 = @q4, qper4 = @qper4, pic1 = @pic1, pic2 = @pic2, pic3 = @pic3, esigdt = @esigdt, CCHName = @CCHName,
CCHTitle = @CCHTitle, CCHsigdt = @CCHsigdt, username = @username, levent = @levent, eventdate = @eventdate, eventtime = @eventtime
WHERE (ePRN = @ePRN)
and the code behind which i have to write will be something like thiscmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@eName", ((TextBox)FormView1.FindControl("TextBox1")).Text);cmd.Parameters.AddWithValue("@ePRN", ((TextBox)FormView1.FindControl("TextBox2")).Text);
cmd.Parameters.AddWithValue("@cID", ((TextBox)FormView1.FindControl("TextBox3")).Text);cmd.Parameters.AddWithValue("@eCC", ((TextBox)FormView1.FindControl("TextBox4")).Text);
((TextBox)FormView1.FindControl("TextBox7")).Text = ((TextBox)FormView1.FindControl("TextBox7")).Text + ((TextBox)FormView1.FindControl("TextBox6")).Text + ((TextBox)FormView1.FindControl("TextBox5")).Text;cmd.Parameters.AddWithValue("@sDate", ((TextBox)FormView1.FindControl("TextBox7")).Text);
cmd.Parameters.AddWithValue("@eLOC", ((TextBox)FormView1.FindControl("TextBox8")).Text);cmd.Parameters.AddWithValue("@eTel", ((TextBox)FormView1.FindControl("TextBox9")).Text);
cmd.Parameters.AddWithValue("@ePhone", ((TextBox)FormView1.FindControl("TextBox10")).Text);
cmd.Parameters.AddWithValue("@eMobile", ((TextBox)FormView1.FindControl("TextBox11")).Text);
So is there any way to do it better than this way ??
Thank you

View 2 Replies View Related

Custom Code (Embedded Code) Question

Oct 16, 2007



Hi all,

Could someone tell me if custom code function can capture the event caused by a user? For example, onclick event on the rendered report?

Also, can custom code function alter the parameters of the report, or refresh the report?

Thanks.

View 2 Replies View Related

Gridview In Asp.net

Nov 29, 2006

Can I directly Save data to sqlserver 2005 using gridview in frontend?
 
How?
 
 

View 2 Replies View Related

GridView Help

Feb 4, 2007

Hi,
I use WVD and SQL Express 2005.
I have a table “SignIn� that one of fields inserted automatically by getdate()
And I have GridView that I use to display this table because I would like take advantage of GridView sorting and paging methods that are embedded in.
Currently I display all records at once.
 
My problem is how to make the GridView show today’s records only.
I tried this code below, but I get only this message “There are no data records to display.�
 
 
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:RC1 %>"
ProviderName="<%$ ConnectionStrings:RC1.ProviderName %>"
SelectCommand="SELECT [student_ID], [SignIn], [SignOut], [Location] FROM [Stud_data] WHERE (CONVERT(VARCHAR(10),[SignIn],101) = @SignIn)">
     <SelectParameters>
       <asp:QueryStringParameter Name="SignIn" QueryStringField="Format(Now, &quot;M/dd/yyyy&quot;)" Type="DateTime" />
     </SelectParameters>
</asp:SqlDataSource>
 
Help Please!
 

View 6 Replies View Related

Gridview

Apr 17, 2008

Hi
I have a business search box and gridview pair. When the user enters a business name, the search results are displayed. I also generate a "more information" link which takes the user to a new page, passing the business name ("memberId")to this page (see the template field below).
The problem I have is if the name contains a QUOTE (') or other special characters. The "memberId" is chopped off at the quote (e.g. "Harry's Store" is passed as "Harry").
Can anyone tell me a way around this please? Is there anything I can do with the Eval method?
Kind regards,
Garrett
 
<asp:TemplateField HeaderText="More Info">
<ItemTemplate>
<a href='member_page.aspx?memberId=<%# Eval("co_name") %>'>more</a>
</ItemTemplate>
<ItemStyle Font-Bold="False" />
</asp:TemplateField>

View 2 Replies View Related

???GridView

Mar 29, 2006

HiI need to add in gridview control  asp code "delete from t1 where id=@id1"how to declare @id1 because the server give me mistake down is the code of asp i use GridView how i can link @id with field there id???Thank u and have a nice daybest regardsthe code if u need it i use c#
<ASP:SQLDATASOURCE id=SqlDataSource1 <br ConnectionString="<%$ ConnectionStrings:libraryConnectionString %>" runat="server"><BR></ASP:SQLDATASOURCE></ASP:BOUNDFIELD>

View 1 Replies View Related

Datatable From Gridview

Aug 2, 2006

hi all
 
the usual way to bid a gridview is to data soursce
is there a way to do  the folowing , creat a data table from the gridview shown valus " currunt page "
 
thanks
 

View 1 Replies View Related

Gridview Sorting

Aug 17, 2006

I have a gridview that has AllowSorting="true" however I need to implement my own sorting because I have DateTime and Integer data types in several of the columns and I don't want an int column sorted like 1,12,2,23,3,34,4,45,5,56, etc.  So, I've added SortParameterName="sortBy" and adjusted my stored procedure to accept this.  For only ASC sorting, I've got
ORDER BY  CASE WHEN @sortBy='' THEN DateCreated END,  CASE WHEN @sortBy='DateCreated' THEN DateCreated END
and so on.  However, columns can also be sorted with DESC.  I tried CASE WHEN @sortBy='DateCreated DESC' THEN DateCreated DESC END, but I get a syntax error on DESC.  How can I do this?

View 2 Replies View Related

Gridview And DropDownList

Oct 18, 2006

Hello:I have add a DropDownList to my GridView and binded the dropdownlist to a field from a select statement in the SQLDataSource. I have EnabledEditing for my GridView. The GridView is populated with information from the select statement. Some of the information returned from the select statement is null. The field where the dropdownlist is binded it is null in some cases and does not have a value that is in the dropdownlist so I get and error when I attempt to do an update. 'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.Parameter name: value Is there a way to get around this besides initializing all the columns in the table that are going to be binded to a dropdownlist to a value in the dropdownlist?

View 1 Replies View Related

Gridview Search

Jan 15, 2007

I tried doing a text box search within Gridview. My code are as follows. However, when I clicked on the search button, nothing shown.
Any help would be appreciated. I'm using an ODBC connection to MySql database. Could it be due to the parameters not accepted in MySql?
 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
 
           SqlDataSource1.SelectCommand = "SELECT * FROM carrier_list WHERE carrierName LIKE '%' + @carrierName + '%'"
 
End Sub
 
Sub doSearch(ByVal Source As Object, ByVal E As EventArgs)
GridViewCarrierList.DataSourceID = "SqlDataSource1"
GridViewCarrierList.DataBind()
 
End Sub
 
HTML CODES (Snippet)
<asp:Button ID="btnSearchCarrier" runat="server" onclick="doSearch" Text="Search" />
' Gridview<asp:GridView ID="GridViewCarrierList" runat="server" DataSourceID="SqlDataSource1" >
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="SELECT * FROM carrier_list">
</asp:SqlDataSource>
 
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>">
<SelectParameters>
<asp:ControlParameter ControlID="txtSearchCarrier" Name="carrierName" PropertyName="Text" Type="String"></asp:ControlParameter>
</SelectParameters>
 
</asp:SqlDataSource>

View 8 Replies View Related

GridView...Problem

Mar 29, 2007

I m creating the project in asp.net using c# and vb languages in 2005.I have used the asp standard controls(with table<td><tr>) and gridview to design the form.I m using sqldatasource to insert and  update data from sql server 2005.I have written the following code  <script runat="server">     Private  Sub Page_Load()        If Not Request.Form("SUBMIT") Is Nothing Then            srccompany.Insert()        End If    End Sub</script>   <asp:SqlDataSource        id="srccompany"        SelectCommand="SELECT * FROM companymaster"        InsertCommand="INSERT companymaster(companyname)           VALUES (@companyname)"      UpdateCommand="UPDATE companymaster SET companyname=@companyname WHERE companyid=1"       DeleteCommand="DELETE companymaster WHERE companyname=@companyname"        ConnectionString="<%$ ConnectionStrings:companymaster %>"       Runat="server"></asp:SqlDataSource>   <asp:GridView        id="GridCompanyMaster"        DataSourceID="srccompany"        Runat="server" />Please help me to insert the data in sql server.i m not been able to insert the data is there any problem in coding..Also i m not been able to edit the data and store back to sql server.Only i can do is i can view the contents in gridview Please give me some tips  

View 1 Replies View Related

SQL OutputCache GridView

Oct 24, 2007

I'm trying to cache the contents of a gridivew unless another page, or sorting method are being called.  I tried to use the VaryByParam method, but I'm not having any luck, I keep getting the same page sent back to me. Here's what my code looks like.
<%@ OutputCache Duration="180" VaryByParam="Page$, Sort$" %>
 Any help would be appreciated.
Stephen

View 2 Replies View Related

Gridview Sql Timeout

Dec 3, 2007

I have a simple gridview displaying data from an MSSQL server 2005. Every now and then I get a sql timeout error. Listed below. Can anyone explain why I am getting this error?  The connection pool is 100 and the timeout is set to 360.  I have checked to current connections in SQL and they never max over 23.  There are not locks in SQL when the problem occurs. The query is a stored procedure in sql and when sent sample data it normally takes about 5 seconds.
 
 Event code: 3005 Event message: An unhandled exception has occurred. Event time: 12/3/2007 9:46:37 PM Event time (UTC): 12/4/2007 3:46:37 AM Event ID: 140501f9a7744dfea2e445ed00939e44 Event sequence: 42 Event occurrence: 1 Event detail code: 0  Application information:     Application domain: /LM/W3SVC/1/ROOT-1-128412128787656250     Trust level: Full     Application Virtual Path: /     Application Path: c:inetpubwwwroot     Machine name: DD-MAIN  Process information:     Process ID: 5544     Process name: w3wp.exe     Account name: NT AUTHORITYNETWORK SERVICE  Exception information:     Exception type: SqlException     Exception message: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.  Request information:     Request URL: http://localhost/Search_DG.aspx?SearchWord=1212     Request path: /Search_DG.aspx     User host address: 10.10.10.1     User:      Is authenticated: False     Authentication Type:      Thread account name: NT AUTHORITYNETWORK SERVICE  Thread information:     Thread ID: 1     Thread account name: NT AUTHORITYNETWORK SERVICE     Is impersonating: False     Stack trace:    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.SqlDataReader.SetMetaData(_SqlMetaDataSet metaData, Boolean moreInfo)   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)   at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()   at System.Data.SqlClient.SqlDataReader.get_MetaData()   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)   at System.Web.UI.WebControls.SqlDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments)   at System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback)   at System.Web.UI.WebControls.DataBoundControl.PerformSelect()   at System.Web.UI.WebControls.BaseDataBoundControl.DataBind()   at System.Web.UI.WebControls.GridView.DataBind()   at System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound()   at System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls()   at System.Web.UI.Control.EnsureChildControls()   at System.Web.UI.WebControls.GridView.get_Rows()   at Install_DG.Page_Load(Object sender, EventArgs e)   at System.Web.UI.Control.OnLoad(EventArgs e)   at System.Web.UI.Control.LoadRecursive()   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)  Custom event details:
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

View 3 Replies View Related







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