Binding A SqlDataSource, To A GridView At Runtime
Mar 8, 2006
Hello
I'm experiencing some problems, binding a SqlDataSource to a GridView.
The following code creates the SqlDataSource:
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string strProvider = ConfigurationManager.ConnectionStrings["ConnectionString"].ProviderName;
SqlDataSource ds = new SqlDataSource(strProvider, strConn);
ds.SelectCommand = "SELECT * FROM rammekategori";
Then i bind the SqlDataSource to a GridView:
GridView1.DataSource = ds;
GridView1.DataBind();
ErrorMessage:
Format of the initialization string does not conform to specification starting at index 0.
Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.
Line 24: GridView1.DataBind();
Am i totally off target here? Can it be something about, that you have to set the datasource of the gridview, before the Page_Load event?
Thanks - MartinHN
View 9 Replies
ADVERTISEMENT
Mar 3, 2008
i am using 2 textbox to search name and instituition of some students. on button click need to display the result on gridview. but i dont get any result.. pl adviceSqlDataSource1.SelectCommand = "SELECT Sname, Address, Instituition, Role, Testgroup, Email FROM std_det WHERE (Sname LIKE '%'+@Param1+'%') AND (Instituition = 'RASET') AND (Role LIKE '%'+@Param2+'%') AND (Instituition = 'RASET')"; name.ControlID = "TextBox3"; name.DefaultValue = "%"; name.Name = "Param1"; name.PropertyName = "Text"; inst.ControlID = "TextBox4"; inst.DefaultValue = "%"; inst.Name = "Param2"; inst.PropertyName = "Text"; //SqlDataSource1.Select(DataSourceSelectArguments.Empty); SqlDataSource1.SelectParameters.Add(name); SqlDataSource1.SelectParameters.Add(inst); SqlDataSource1.DataBind(); //DataView dv = (DataView)this.SqlDataSource1.Select(DataSourceSelectArguments.Empty); GridView2.DataSourceID = "SqlDataSource1"; GridView2.DataBind();
View 2 Replies
View Related
Mar 20, 2008
Hey guys, Am in need of help please, basically the program im working with at the moment is when you add a New Contract, it will grab the Contract Number you have entered, Post it over to another page, then using that number bind a Gridview. The SQL being "SELECT Contract_ID, Contract_Number, Start_Date, End_Date, Quarterly_Rent FROM ECS_Contracts_Test WHERE Contract_Number = " & conNoVar (this being the Contract Number of the recently added Contract), however then it comes to Bind the Grid it kicks up an System.Data.SqlClient.SqlException: Syntax error converting the nvarchar value
'2009P7899' to a column of data type int.But the Column Contract_Number is set to Varchar and all I really want to do is to create this gridview using this criteria and not convert anything! The Contract_ID is an int, which is needed as I increment it. Heres the error code: Public Sub BindtheGrid()'Bind the Contract Grid, where ContractID is used
Dim SQL As String = "Contract_ID, Contract_Number, Start_Date, End_Date, Quarterly_Rent"
Dim objConn As SqlConnection = New SqlConnection(ConnectionString)
Dim cmdstock As SqlCommand = New SqlCommand("SELECT " & SQL & " FROM ECS_Contracts_Test WHERE Contract_Number = " & contractQueryID, objConn)
cmdstock.CommandType = CommandType.Text
objConn.Open()
GridView1.DataSource = cmdstock.ExecuteReader()
GridView1.DataBind()
objConn.Close()
End Sub If you need any more information then please let me know. Mucho Aprreciated
View 1 Replies
View Related
Jul 30, 2007
Hi all,
The Scenario:
Database1:Table1(callingPartyNumber,originalCalledPartyNumber, finalCalledPartyNumber, DateTimeConnect, DateTimeDisconnect, Duration)
Database2:Table2(Name,Number)
Output in Gridview:
callingPartyNumber
Name
originalCalledPartyNumber
finalcalledPartyNumber
dateTimeConnected
dateTimeDisconnected
Duration (HH:MM:SS)
I bind gridview programatically using DataTable and stored procedures. The data comes from a table (Table1) in a database (Database1) on SQL Server. The gridview displays fields callingPartyNumber, originalCalledPartyNumber, finalCalledPartyNumber, DateTimeConnect, DateTimeDisconnect and Duration in this order. All the columns in this gridview are databound columns.
I have another table (Table2) in a seperate SQL Server database (Database2) but on the same server which maps the callingPartNumber value with the name attached with that number. Note that the field names in Table2 are different from the field names in Table1. Is it possible to display the Name field also in the gridview after the first field callingPartyNumber and then the other fields.
Its like data coming from two tables into the gridview.
Thanks
View 7 Replies
View Related
Jun 19, 2007
Hello All, I am new to data access and
i have got the problem to display the data into the page by binding the gridview with sqlConnection, sqlCommand and sqlDataReader objects. The actually code is written as:protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{SqlConnection myConnection;
SqlCommand myCommand;SqlDataReader myReader;
myConnection = new SqlConnection();myConnection.ConnectionString = ConfigurationManager.ConnectionStrings["LatteConnectionString"].ConnectionString;
myCommand = new SqlCommand();myCommand.CommandText = "select * from AntiVirusVendors";myCommand.CommandType = CommandType.Text;
myCommand.Connection = myConnection;
myCommand.Connection.Open();myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = myReader;
GridView1.DataBind();
myCommand.Dispose();
myConnection.Dispose();
}
}
and the GridView in html is listed as:
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
So the problem is ---> there is nothing shown in the page, no errors no anything.... just the empty page.
Any ideas would be appreciated. Thanks in advance!
Joe
View 1 Replies
View Related
Jan 21, 2008
Hi All
I am trying to bind a gridview to my sql express database through code but my data is not being displayed, i dont get any errors though?
If i bind it using an sql datasource it works fine so i know my connection string works and there is data in my database
my code is as follows
thanks
gibbo
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ReadRecords(GridView1, "Select * from Actions")
End Sub
Public Shared Function GetConnString() As String
Return System.Configuration.ConfigurationManager.ConnectionStrings("actionsConnectionString2").ConnectionString
End Function
Private Sub ReadRecords(ByVal datagrid As GridView, ByVal SQL As String)
Dim ConnString As String = GetConnString()
Dim SqlString As String = SQL
Using conn As New SqlClient.SqlConnection(ConnString)
Using cmd As New SqlClient.SqlCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
conn.Open()
Using reader As SqlClient.SqlDataReader = cmd.ExecuteReader()
datagrid.DataSource = reader
datagrid.DataBind()
End Using
End Using
End Using
End Sub
Connection String
<add name="actionsConnectionString2" connectionString="Data Source=.SQLEXPRESS;AttachDbFilename="|DataDirectory|actions.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
View 8 Replies
View Related
Dec 14, 2007
Hi All,
I have written a Query and Stored Procedure in SQL 2000 which fetched around 15 Lac data. It takes around 17 seconds to fetch the data in the Query Analyzer. But when i am using the Query/Stored Procedure in the report and I have deployed it in the server. When i am accessing the report in the application it taking around 2-3 minutes to bind the data.
What might be the issue? My tables in the database has been normalized.
Please help me to sort out this problem.
Regards
View 15 Replies
View Related
Dec 21, 2007
Hi
I am binding SQLdatasource with the Gridview at runtime that works fine, but i have mentioned the update command as well, but grid is not updating, there is no error, but after clicking update, no thing happens and grid returns to last state.
Part of code is :
void btnshowdata_click(){
SqlDataSource1.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
SqlDataSource1.SelectCommand = "dbo.getAllOutstanding";
SqlDataSource1.UpdateCommand = "UPDATE SPS_Oustandings SET Status = @Status, Comments = @Comments WHERE (Inv_No = @Inv_no)";
grid.DataBind();
}
datasource is already attached to grid, but its select query is chaning at button click. At design time binding update works but when i click the button binding(select quesry) is changed, after that update is not working.
Any help?
Thanks
View 5 Replies
View Related
Feb 13, 2007
This is an easy question. I thought I have databinded a textbox to a SQLDataSource. But now I do not see how to do that now. Can somebody help with this?
Thanks,
View 1 Replies
View Related
Mar 9, 2007
Hi, I wants to bind textbox with sqldatasource in c#.net so I am using following code and has following error... Exception Details: System.NullReferenceException: Object reference not
set to an instance of an object.Source Error:
Line 22: Line 23: System.Data.DataView dv = (DataView) SqlDataSource1.Select(System.Web.UI.DataSourceSelectArguments.Empty);Line 24: TextBox1.Text = dv[0]["Proid"].ToString();Line 25: Line 26: }Please, anybody knows solution tell me
View 1 Replies
View Related
Jan 10, 2006
Hi, I am using a SQL DataSource with a few parameters. I need to specify the value of the parameters at run time but I need a custom way to do it as the value needs to be calculated not come from Cookie, Control, Form, Profile, QueryString or Session. Is there a way to bind your own value to these parameters. For instance if I had a variable how would I bind that to the parameter?
At the moment i am doing the following which works but I dont think it is the correct way
dsMyDataSource.SelectParameters["MyParameter"].DefaultValue = MyCalculatedValue;
In previous projects i have added a value to the Session and then bound the parameter value to the session but that doesnt seem like a good solution either.
Thanks for any help you can give.
Martin
View 9 Replies
View Related
Oct 6, 2006
Hello, I just started working with ASP.NET.I'm trying to use the CheckBoxList Control. As I understand it, you can bind a SqlDataSource to this control and it loads the list for you. However tp precheck the items, you have to do this manually. This part works fine. Next part was to save whatever the user checks. I wrote stored Procedure and now just trying to pass 1 parameter to the stored procedure using a second SqlDataSource. I get the error: "A severe error occurred on the current command. The results, if any, should be discarded."Here is the second datasource I am using to try and save the data:<asp:SqlDataSource ID="sds_PersonRole" runat="server" ConnectionString="<%$ ConnectionStrings:Development %>"SelectCommand="usp_selectPersonRole"SelectCommandType="StoredProcedure"UpdateCommand="usp_updatePersonRole"UpdateCommandType="StoredProcedure"><SelectParameters> <asp:ControlParameter ControlID="gv_Person" Name="PERSON_ID" PropertyName="SelectedValue" Type="Int32" /></SelectParameters><UpdateParameters> <asp:Parameter Name="strXML" Size="8000" Type="String" /> <asp:Parameter Direction="InputOutput" Name="err_msg" Type="String" Size="150" DefaultValue="0" /></UpdateParameters></asp:SqlDataSource>I have a code behind file with the following modules: (btnEditPerson is clicked to start the process. the sds_PersonDetails is updated via form contolls and works fine.) Error occurs on the bolded line (Stored procedure is just accepting the string and saving to a field. It works fine, I tested it. Its just erroring out before it runs the stored procedure. Protected Sub btnEditPerson_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnEditPerson.Click sds_PersonDetails.Update() gv_Person.DataBind() sds_PersonRole.Update()End Sub Protected Sub sds_PersonRole_Updating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles sds_PersonRole.Updating Dim command As Data.Common.DbCommand command = e.Command 'un-check all checkboxlist items (count - 1 to account for starting at 0) Dim listCount As Integer = cbl_Role.Items.Count() - 1 Dim strXML As String strXML = "<personRole>" For x As Integer = 0 To listCount If cbl_Role.Items(x).Selected() = False Then strXML = strXML & "<person id='" & gv_Person.SelectedValue & "' />" strXML = strXML & "<role id='" & cbl_Role.Items(x).Value & "' />" End If Next strXML = strXML & "</personRole>" command.Parameters("@strXML").Value = strXML lbl_ErrMsg.Text = command.Parameters("@err_msg").Value.ToString() End Sub
View 1 Replies
View Related
Feb 28, 2007
I have a SQL database with 1 column in it.. it is a do not call registry for my office. I want to make a web application so our leads can go on the web and request to be put on the do not call list. problem is, if their number already exists, it gets a violation of primary key... Normal handling for this would be to do a select query based on user input, and if it exists in the database, tell them that, else do the insert query... Problem is, i cant seem to figure out how to bind the result of the select query to a textbox or label so i can compare the results to do that logic. Any ideas? This is in asp .net 2.0. Thanks! -Dan
View 5 Replies
View Related
Oct 26, 2007
Ive run into a situation where some code im using will not function the same when between these two cases. So, this has me wondering what is going on behind the scenes. What is the sequence of events that are occurring that would possibly be messing things up.Here is the sample codeIts a gridview that is using a sqldatasource control. The code works fine, but if you want to bind the grid to a dataset and call databind yourself, things dont work as expected and the other features that the code performs just isnt happening, at least not for me.
View 1 Replies
View Related
May 3, 2008
i have a gridview which is bound to sqldatasource. i have a delete button in the gridview. I have written code for "deleting" a record in app_code directory.
now iam not using "deletecommand" of sqldatasource but on the click of "delete" link i want to call the procedure in the app_code.
Any ideas on how to do it.??
View 4 Replies
View Related
Apr 14, 2006
I have created a GridView that uses a SqlDataSource. When I run the page it does not pull back any data. However when I test the query in the SqlDataSource dialog box it pulls back data.
Here is my GridView and SqlDataSource:
<asp:GridView ID="Results" runat="server" AllowPaging="True" AllowSorting="True"
CellPadding="2" EmptyDataText="No records found." AutoGenerateColumns="False" Width="100%" CssClass="tableResults" PageSize="20" DataSourceID="SqlResults" >
<Columns>
<asp:BoundField DataField="DaCode" HeaderText="Sub-Station" SortExpression="DaCode" >
<ItemStyle HorizontalAlign="Center" CssClass="tdResults" />
<HeaderStyle HorizontalAlign="Center" CssClass="tdHeaderResults" />
</asp:BoundField>
<asp:BoundField DataField="DpInfo" HeaderText="Delivery Point" SortExpression="DpInfo" >
<HeaderStyle HorizontalAlign="Left" CssClass="tdHeaderResults" />
<ItemStyle CssClass="tdResults" />
</asp:BoundField>
<asp:HyperLinkField DataNavigateUrlFields="CuCode,OrderID" DataNavigateUrlFormatString="TCCustDetail.asp?CuCode={0}&OrderID={1}"
DataTextField="OrderID" HeaderText="Order No" SortExpression="OrderID">
<ItemStyle CssClass="tdResults" HorizontalAlign="Center" />
<HeaderStyle CssClass="tdHeaderResults" HorizontalAlign="Center" />
</asp:HyperLinkField>
<asp:BoundField HeaderText="Order Date" SortExpression="OrderDate" DataField="OrderDate" >
<ItemStyle HorizontalAlign="Center" CssClass="tdResults" />
<HeaderStyle HorizontalAlign="Center" CssClass="tdHeaderResults" />
</asp:BoundField>
<asp:BoundField DataField="ReqDeliveryDate" HeaderText="Req Delivery Date" SortExpression="ReqDeliveryDate" >
<ItemStyle HorizontalAlign="Center" CssClass="tdResults" />
<HeaderStyle HorizontalAlign="Center" CssClass="tdHeaderResults" />
</asp:BoundField>
<asp:BoundField DataField="StatusDate" HeaderText="Status Date" SortExpression="StatusDate">
<ItemStyle HorizontalAlign="Center" CssClass="tdResults" />
<HeaderStyle HorizontalAlign="Center" CssClass="tdHeaderResults" />
</asp:BoundField>
<asp:BoundField DataField="ManifestNo" HeaderText="Manifest No" SortExpression="ManifestNo">
<ItemStyle HorizontalAlign="Center" CssClass="tdResults" />
<HeaderStyle HorizontalAlign="Center" CssClass="tdHeaderResults" />
</asp:BoundField>
<asp:BoundField DataField="CustomerPO" HeaderText="P.O. No" SortExpression="CustomerPO">
<ItemStyle HorizontalAlign="Center" CssClass="tdResults" />
<HeaderStyle HorizontalAlign="Center" CssClass="tdHeaderResults" />
</asp:BoundField>
<asp:BoundField DataField="Class" HeaderText="Class" SortExpression="Class">
<ItemStyle HorizontalAlign="Left" CssClass="tdResults" />
<HeaderStyle HorizontalAlign="Left" CssClass="tdHeaderResults" />
</asp:BoundField>
<asp:BoundField DataField="OrderStatus" HeaderText="Order Status" SortExpression="StatusSort">
<ItemStyle HorizontalAlign="Left" CssClass="tdResults" />
<HeaderStyle HorizontalAlign="Left" CssClass="tdHeaderResults" />
</asp:BoundField>
</Columns>
<HeaderStyle ForeColor="White" HorizontalAlign="Left" />
<AlternatingRowStyle CssClass="tdResultsAltRowColor" />
</asp:GridView>
<asp:SqlDataSource ID="SqlResults" runat="server" ConnectionString="<%$ ConnectionStrings:TransportationConnectionString %>" SelectCommand="GetOrderSummaryResults" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="10681" Name="CuCode" Type="String" />
<asp:Parameter DefaultValue="" Name="DaCode" Type="String" />
<asp:Parameter DefaultValue="" Name="DpCode" Type="String" />
<asp:Parameter DefaultValue="" Name="OrderID" Type="String" />
<asp:Parameter DefaultValue="" Name="ManifestNo" Type="String" />
<asp:Parameter DefaultValue="" Name="PONo" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
I can get it to fill with data by manually filling the GridView without using a SqlDataSource but then I cannot get the sorting to work when I do it that way. Actually not sure if the sorting will work this way either as I cannot get it to fill with data. Any ideas would be much appreciated.
View 1 Replies
View Related
Oct 31, 2006
Hi guys.Im using a gridview to show some training data on my website which is populated by:<asp:SqlDataSource ID="ARENATraining" runat="server" ConnectionString="<%$ ConnectionStrings:ARConnection %>" SelectCommand="SELECT [EventType], [CourseLink], [EventDate], [EventTitle], [EventLocation], [EventWebsite] FROM [qry_FutureEvents] WHERE ([EventPrivate] = @EventPrivate) ORDER BY [EventDate]"> <SelectParameters> <asp:Parameter DefaultValue="FALSE" Name="EventPrivate" Type="Boolean" /> </SelectParameters> So far so good..However I want to be able to filter the data.A) Show everythingB) Show individual EventType i.e. Seminar, Training etc etcIs it possible to generate the Select Command via a function? (im not using stored procedures for this part of the site, nor really want to at the moment). Id appreciate any help, otherwise ill be forced to curse and swear and use the good ol repeater and figureing out how to page it! Cheers guys
View 6 Replies
View Related
Jan 28, 2007
i am now writing a web page which can allow users to edit the field(display in the gridview->gridview source is from sqldatasource), there is a problem(it seems that i have followed all steps in the book):
when the i edit the field and click update, in the web site, i can see those changes. however, i cant see any change in database table.
i cant find solution on this, could anyone help me to solve this problem? thx!
View 2 Replies
View Related
May 11, 2007
Hello.When I create a user at the ASP.NET database, I need to insert more fields than the defaults, and I do it like this: Dim customProfile As ProfileCommon = ProfileCommon.Create(CreateUserWizard1.UserName, True)
customProfile.telephone =
(CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("TelephoneText"),
TextBox)).Text(telephone example)Those data are inserted at the DB at the aspnet_Profile table, in the fields PropertyNames & PropertyValuesString, but they are saved together (see image above)
I want to separate those properties in the GridView as long as each property appears in a column, is it possible? Thank you very much, i'm expecting your answers.
View 11 Replies
View Related
Jan 12, 2008
hi .. i have a SqlDataSource, GridView & a Button .. i want to increase the condition in the "SelectCommand" below by one everytime i click the button .. i mean to be like that ID < 8 instead of ID < 7
so, the GridView will show 7 ID's instead of 6 .. and it will increase everytime i hit the button<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:connectionstring %>"
SelectCommand="SELECT * FROM [table1] WHERE ID < 7">
</asp:SqlDataSource>
View 4 Replies
View Related
Aug 21, 2006
What is the easiest way to obtain number of records in SQLDataSource (using select statement)/GridView. All that I've found in forums seems to be very difficult for such trivial task... Thank you!
View 4 Replies
View Related
Apr 15, 2008
Hi
I have a gridview which is using a SQLdatasource, to update the table. One of my parameters on the SP is username.
At the moment on page load I am declaring a session variable
Session("UserName") = me.user.identy.name
I then amend the update parameter in the SQL Datasource to accept the username from the session variable. - works fine, I was however wondering if there is a way of returning the username directly into the sqldatasource without having to pass it through a session variable?
regards
Tom
View 3 Replies
View Related
May 2, 2008
Hi guys! I have a simple windows form where a gridview is being populated by a database. I have checked the ability to update, insert delete. And everything is fine but when i want to delete a row it throws an exeption. The exeptions says: "Must declare the scalar variable "@id"."I haven't changed the delete, update and insert commands. They are as fallowsDeleteCommand="DELETE FROM [recepti] WHERE [id] = @id"InsertCommand="INSERT INTO [recepti] ([ime], [recepta], [snimka], [snimka2], [tip]) VALUES (@ime, @recepta, @snimka, @snimka2, @tip)" SelectCommand="SELECT * FROM [recepti]"UpdateCommand="UPDATE [recepti] SET [ime] = @ime, [recepta] = @recepta, [snimka] = @snimka, [snimka2] = @snimka2, [tip] = @tip WHERE [id] = @id" The id column is auto generated, unique, also it's a primery key.So any idea where is the problem?
View 2 Replies
View Related
May 19, 2008
Hi,I have two SQLDataSources called "LeagueTableHome" an "LeagueTableAway" on my page.
I want to create another SQLDataSource called "LeagueTableTotal" on my page which adds up all the totals from each of the other two sources.
The datasource looks like this:
Team, Pld, W, D, L, F, A, Agg, Pts
my code for LeagueTableHome looks like this:
SELECT HomeTeam, 1 AS Pld, CASE WHEN HomeScore > AwayScore THEN 1 ELSE 0 END AS Won, CASE WHEN HomeScore = AwayScore THEN 1 ELSE 0 END AS Draw, CASE WHEN HomeScore < AwayScore THEN 1 ELSE 0 END AS Lost, HomeScore AS Scored, AwayScore AS Against, HomeScore - AwayScore AS Agg, CASE WHEN HomeScore > AwayScore THEN 3 ELSE 0 END AS Pts FROM tblFixtures WHERE (CompID = 1) AND (HomeScore IS NOT NULL)
I want then to show LeagueTableTotal in a GridView.
Can anybody help?
View 4 Replies
View Related
May 19, 2008
I cant seen to change the Select command for a SQL Datasourcetry #1 SqlDataSourceProfilesThatMatch.SelectCommand = strSQLForSearch SqlDataSourceProfilesThatMatch.SelectParameters("ProfileID").DefaultValue = pProfileID SqlDataSourceProfilesThatMatch.SelectParameters("LoggedInUsersZipcode").DefaultValue = pUsersZipCode SqlDataSourceProfilesThatMatch.SelectParameters("ZipDistance").DefaultValue = pDistance
NewProfilesThatMatchGridView.DataBind()
try #2 SqlDataSourceProfilesToBeMatched.SelectParameters.Clear() SqlDataSourceProfilesThatMatch.SelectCommand = strSQLForSearch SqlDataSourceProfilesThatMatch.SelectParameters.Add("ProfileID", pProfileID) SqlDataSourceProfilesThatMatch.SelectParameters.Add("LoggedInUsersZipcode", pUsersZipCode) SqlDataSourceProfilesThatMatch.SelectParameters.Add("ZipDistance", pDistance)
NewProfilesThatMatchGridView.DataBind()
No errors but no rows show in the gridview. If I debug and get the value strSQLForSearch and paste it into a new SQL query window I get results.
Any ideas????
Thanks
View 3 Replies
View Related
Apr 17, 2006
Help!I am trying to fill my datagrid using the SQLDataSource, using a stored procedure.The stored procedure expects a parameter which I can collect via the querystring, or a string. How can I pass the parameter through the SQLDatasSource?My SQLDataSource is SQLData1. I already have:SQLData1.SelectCommandType = SqlDataSourceCommandType.StoredProcedureSQLData1.SelectCommand = "dbo.get_players"Thanks in advance,Karls
View 2 Replies
View Related
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
Dec 8, 2006
Hi!
My question is exactly the subject.
My Web Form has only a GridView and a DetailsView, there is no SqlDataSource at project time, i create the SqlDataSource at runtime using code like this in the Page_Load event: (I NEED IT TO BE CREATED DYNAMICALLY)1 Dim SQLDS As SqlDataSource = New SqlDataSource()
2
3 SQLDS.ID = "CustomerDataSource"
4 SQLDS.ConnectionString = ConfigurationManager.ConnectionStrings("connectionstring").ConnectionString
5 SQLDS.SelectCommand = "select customerid,companyname,contactname,country from customers"
6 SQLDS.InsertCommand = "insert into customers(customerid,companyname,contactname,country) values(@customerid,@companyname,@contactname,@country)"
7 SQLDS.UpdateCommand = "update customers set companyname=@companyname,contactname=@contactname,country=@country where customerid=@customerid"
8 SQLDS.DeleteCommand = "delete from customers where customerid=@customerid"
9
10 SQLDS.UpdateParameters.Add(New Parameter("companyname"))
11 SQLDS.UpdateParameters.Add(New Parameter("contactname"))
12 SQLDS.UpdateParameters.Add(New Parameter("country"))
13 SQLDS.UpdateParameters.Add(New Parameter("customerid"))
14
15 Page.Controls.Add(SQLDS)
16
17 If Not Page.IsPostBack Then
18 GridView1.DataKeyNames = New String() {"customerid"}
19 GridView1.DataSourceID = SQLDS.ID
20
21 ' ... and so on
The DetailsView1 uses the same SqlDataSource to show data, but i could not find a way to synchronize the DetailsView1 with the GridView1 when a record is selected in the GridView1.How can I synchronize the DetailsView?I played with the ControlParameter but i can't find either how to add a ControlParameter in code, is there a way? Every place talking about ControlParameter shows something like this: 1 <asp:SqlDataSource ID="SqlDataSource1" runat="server"
2 ConnectionString="<%$ ConnectionStrings:Pubs %>"
3 SelectCommand="SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors] WHERE [state] = @state">
4 <SelectParameters>
5 <asp:ControlParameter Name="state" ControlID="DropDownList1" PropertyName="SelectedValue" />
6 </SelectParameters>
7 </asp:SqlDataSource>
8
Ok. OK. But my SqlDataSource is created dynamically. Any ideas on how to solve this problem?Thanks!
View 3 Replies
View Related
Oct 31, 2007
In a web site the user has to choose one out of several sql tables to deal with.
He will then be allowed to view the selected table data through a GridView, to insert a new row into and to update a row in the selected table by means of an array of TextBoxes created dynamically on the base of the selected table.
I think it is possible to solve the problem fully by properly configuring at run time an SqlDataSource.
I have solved the issue of data display by declaring in the code behind within the OnPageLoad sub the following:
SqlDataSource1.SelectCommand = "Select * FROM " & selectedTable
While for the GridView1 I have added the selected table columns to the columns collection as follows:
for i=0 to ColumnCount-1 Dim cac As BoundField = New BoundField
cac.HeaderText = HeaderNamesArray(i)
cac.DataField = ProductNamesArray(i)Me.GridView1.Columns.Add(cac)
next
I have difficulty on how to do similar declarations for the insertcommand and update command.
View 2 Replies
View Related
Nov 5, 2006
I have a SqlDataSource that I need to remove the first 3 rows from before it is bound to a GridView. How would I go about doing this?
(if I could remove them at the db level in the sproc I would, but right now that is not an option - so I need to do it once I've already received the data)
Thanks.
View 9 Replies
View Related
Jan 9, 2007
Hi,
I have a GridView connected to a sqldatasource control. Everything is working great, updates, paging and filtering with one exception. When the user enters in a name like O'Reilly (with a single quote), the page errors. The error returned is:
Syntax error: Missing operand after 'Reilly' operator.
Here is the definition of the sqldatasource:
<asp:SqlDataSource ID="SqlDataSourcePersons" runat="server" ConnectionString="<%$ ConnectionStrings:database %>" SelectCommand="SELECT [Id], [FirstName], [LastName], , [PersonTypeId], [WorkerId], [_workerNTId], [Title], [City] FROM [Person]" FilterExpression="(FirstName like '{0}%') AND (LastName like '{1}%') AND (WorkerId like '{2}%') AND (City like '{3}%')" ProviderName="System.Data.SqlClient"> <FilterParameters> <asp:ControlParameter ControlID="TextBoxFirstName" Name="FirstName" DefaultValue="%" PropertyName="Text" Type="String" /> <asp:ControlParameter ControlID="TextBoxLastName" Name="LastName" DefaultValue="%" PropertyName="Text" Type="String" /> <asp:ControlParameter ControlID="TextBoxWorkerId" Name="WorkerId" DefaultValue="%" PropertyName="Text" Type="String" /> <asp:ControlParameter ControlID="TextBoxCity" Name="City" DefaultValue="%" PropertyName="Text" Type="String" /> </FilterParameters> </asp:SqlDataSource>
Any suggestions would be appreciated.
Thank you, Jim
View 1 Replies
View Related
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
Mar 11, 2007
Hi all, first post, and I am desperate.
I have a SqlDataSource with a Select, Update and Delete command. From what I understand, scalar variables should be read automatically from the GridView's BoundField columns when it executes a command on it. Here is my code:
<asp:GridView
ID="teamGrid"
EmptyDataText="n/a"
DataKeyNames="TeamId"
AutoGenerateColumns="false"
DataSourceID="teamSource"
OnRowEditing="validateEdit"
OnRowDeleting="validateDelete"
runat="server">
<Columns>
<asp:CheckBoxField DataField="TeamApproved" HeaderText="Approved" />
<asp:BoundField DataField="TeamName" HeaderText="Team Name" />
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label runat="server"><%# Eval("City") %></asp:Label>, <asp:Label runat="server"><%# Eval("ProvinceCode") %></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="RequestedDivision" HeaderText="Division Req." ControlStyle-Width="60px" />
<asp:BoundField DataField="DivisionCode" HeaderText="Assigned Division" ControlStyle-Width="60px" ConvertEmptyStringToNull="true" NullDisplayText="n/a" />
<asp:BoundField DataField="DivisionNumber" HeaderText="Division Number" ControlStyle-Width="60px" ConvertEmptyStringToNull="true" NullDisplayText="n/a" />
<asp:BoundField DataField="Password" HeaderText="Password" ConvertEmptyStringToNull="true" NullDisplayText="n/a" />
<asp:CheckBoxField DataField="Paid" HeaderText="Paid" />
<asp:HyperLinkField Text="view players" ItemStyle-Width="70px" ItemStyle-HorizontalAlign="Center" DataNavigateUrlFields="TeamId" DataNavigateUrlFormatString="viewTeamPlayers.aspx?teamId={0}" ShowHeader="false" />
<asp:CommandField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="30px" ButtonType="Link" EditText="edit" ShowEditButton="true" ShowHeader="false" />
<asp:TemplateField ShowHeader="False" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="30px">
<ItemTemplate>
<asp:LinkButton runat="server" CausesValidation="False" CommandName="Delete" OnClientClick='return confirm("Deleting this team will also delete the players. Are you sure you wish to continue?");' Text="delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource
ID="teamSource"
ConnectionString="<%$ ConnectionStrings:MB %>"
SelectCommand="SELECT TeamId, TeamName, ProvinceCode, City, DivisionCode, DivisionNumber, TeamApproved, RequestedDivision, Paid, Password, CaptainId, Player2Id, Player3Id, Player4Id FROM [Team]"
UpdateCommand="UPDATE [Team] SET TeamName = @TeamName, DivisionCode = @DivisionCode, DivisionNumber = @DivisionNumber, TeamApproved = @TeamApproved, Paid = @Paid, Password = @Password WHERE TeamId = @TeamId"
runat="server" />
</form>
I apologize for the way the code is put in, the code thing cut off a lot of the text! The problem I'm getting is, when the 'Update' button is hit, I get the error: Must declare the variable '@TeamId'.
I've tried putting "Update Parameters", that takes away the error, but the row does not update. I've browsed the internet and saw the same problems in lots of areas, but either a) none of the solutions work for me, or b) they don't really apply to my case.
I'm using ASP .NET 2.0, and (obviously) C#. SQL Server database.
Any help is greatly appreciated. Thanks in advance,
- Branden
View 2 Replies
View Related