Showing posts with label sqldatasource. Show all posts
Showing posts with label sqldatasource. Show all posts

Thursday, March 29, 2012

getting the list of connection strings to display in the SqlDataSource Wizard

I've added an SqlDataSource control to my web page and selected "Configure Data Source" on it. This brings up a "Choose Your Data Connection" wizard, and it asks you to select from a dropdown list of presumably pre-existing connection strings in my web.config file. However none of my connection strings will display in that dropdown list. The only thing i can do is hit the "Create New Connection" button and this adds yet another connection string to my web.config file.

I've already ran through the wizard once, created a new connection string, but when i run through the wizard again, even the new connection string - the one created by the last wizard will not appear in the dropdown list.

Any suggestions?

Jason

Hi Jason,

Are the connection strings actually appearing in the web.config file? Are they actually working - that is, if you call one of the connection strings, does it actually do what you expect? I can't offer any actual solutions to this one, but have you tried creating a new web.config file and checking if this fixes the problem? Personally, I would set up a new application just to test this, and if it works OK in the new application then perhaps something in your current application has caused the issue.

Hope this helps.

Paul

|||

Hi Paul - yes i've tried your suggestions before but nothing works. In fact, even after already running "Choose Your Data Connection" wizard (and selecting the new datasource option) to let it generate a datasource for me, and then running the wizard again to see if the previously created datasource will appear, and it doesn't.

Not a big deal i guess but a bit of a pain. I wonder if its a bug...

Jason

|||

Hi Jason,

Please be sure that you have saved the string (a checkbox for you to select) the first time you use it.

Thanks.

sql

Tuesday, March 27, 2012

Getting the automatically generated id after SqlDataSource.Insert()

Hello!

I have a SqlDataSource that inserts some data in a database. The field "id" is auto-increment. Is it possible to use the "id", this data-row got from the database automatically, directly after the SqlDataSource.Insert() command in my CodeBehind file?

Thank you!

You would need to append "SELECT SCOPE_IDENTITY()" to your insert command then retrieve the value in the Inserted event.

More info here (note, this shows a pure ADO.NET approach, but my be of use): http://www.mikesdotnetting.com/Article.aspx?ArticleID=54

|||

Take a look at this FANTASTIC tutorial:

http://www.asp.net/learn/data-access/tutorial-01-cs.aspx

This tutorial has helped me a lot and I am using it now to build an application for our company.

Here you will see detailed instructions on how to create different queries and retrieve the id usingSELECT SCOPE_IDENTITY().


|||

Ah thank you!

I added the "SELECT SCOPE_IDENTITY"-statement at the end of my insertcommand. But if I try

int id = SqlDataSource1.Insert();
it returns me only "1", the number of affected rows.
 How can I tell him to return me the result from the SELECT SCOPE_IDENTITY-statement? 
|||I have never tried using the SqlDataSource to do this kind of thing. It is limited in it's useage. You may have uncovered another limit. You can try changing the insert command to a stored procedure which returns an output parameter, or add an output parameter to the current collection of InsertCommand parameters, or use plain ADO.NET.|||

Folow the instructions bellow and you will get what you need:

1- Create your sql connection statement:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);

2 - Create your insert and select statement together:

SqlCommand newCmd = new SqlCommand("INSERT INTO Orders (FirstName,LastName,Email)" + "Values (@.FirstName,@.LastName,@.Email)" + "SELECT SCOPE_IDENTITY()", conn);

3 - Define your parameters

newCmd.Parameters.Add("FirstName", SqlDbType.NChar, 50).Value = cFirstNTB.Text;

newCmd.Parameters.Add("LastName", SqlDbType.NChar, 50).Value = cLastNTB.Text;

newCmd.Parameters.Add("Email", SqlDbType.NVarChar, 50).Value = cEmailTB.Text;

4 - Then you perform insert/select and get your scope identity:

conn.Open();

newCmd.ExecuteNonQuery();

decimal ThisID =0;

SqlDataReader ServiceReader = newCmd.ExecuteReader();

while (ServiceReader.Read())

{

ThisID = (decimal)ServiceReader.GetValue(0);

}

ServiceReader.Close();

string ThisID = newLeadCmd.ExecuteScalar().ToString();

newLeadconn.Close();

Now, Istrongly advise you to start using Strongly-typed data sets. Take a look at the tutorial in the link I posted before. It will help you do some serious coding.

Take care!

|||

The SqlDataSource's insert internally does a ExecuteNonQuery. Unfortunately, that means that it will throw away the resultset generated by your SELECT SCOPE_IDENTITY().

The easiest way to work around this is to use a parameter value. Add an output parameter to your SqlDatasource's Insert Parameters declaritively. Then add this to the end of your insert command: " SET @.NewParameter=SCOPE_IDENTITY();" Then in the SqlDatasource_Inserted event, pick up the contents of the NewParameter parameter and do what you want with it (possibly setting a class/form level variable).

How to add an output parameter:

Select your SqlDatasource control. In the properties window, find the InsertQuery property and select the "..." button to call up the Command and Parameter editor. Click the Add property button. Click the show advanced properties button. Change the Direction property to "Output". Change the Type to "Int32".

How to retrieve the contents in the SqlDatasource_Inserted event:

Private LastInsertID as integer

ProtectedSub SqlDataSource1_Inserted(ByVal senderAsObject,ByVal eAs System.Web.UI.WebControls.SqlDataSourceStatusEventArgs)Handles SqlDataSource1.Inserted

LastInsertID = e.Command.Parameters("@.NewParameter").Value

EndSub

Now you can either do what you want to do after an insert in your SqlDataSource_Inserted event, or if you need to manually call the insert method of the SqlDatasource you can do something like the following:

SqlDatasource1.Insert()

label1.text=LastInsertID.ToString()

|||

Thank you for your replies!

@.Motley:

That looks good, but I have a little problem with implementing your code. If I place

 protectedvoid SqlDataSource2_On_Inserted(object sender, SqlDataSourceStatusEventArgs e) { newID = (int)e.Command.Parameters["newID"].Value; }

in my CodeBehind file, the newID is always zero. I guess, the problem is, that the name of this method might be wrong.

How do I have to name this method correctly?

Thank you!

|||

Yes you do. If you go to your page in Design view and select the SqlDataSource, hit F4 and you will get the properties window. There is a lightning bolt there. Click that and you will be presented with a list of the control's events. Double click the Inserted event, and it will create an event handler automatically in your code-behind.

|||

It works!Cool Great! Thank you all very much!Yes

Friday, March 23, 2012

Getting Sql Variable value

Hi, Looking for a sample in C# (ASP2.0 vwd) of getting a SqlDataSource Variable (@.uNameID) into a string Variable (string uNameID)

Any help would be appreciated!

<asp:SqlDataSource ID="SqlDataSource3" runat="server" OnSelected="SqlDataSource3_Selected" ConnectionString="<%$ ConnectionStrings:testExpressConnectionString %>"
SelectCommand="SELECT userName, userPWD FROM user_test whereuserName=@.userName ">

<SelectParameters>
<asp:controlParameter Name="userName" Direction="InputOutput" Type="String" ControlID="TextBox1" />

</SelectParameters>
</asp:SqlDataSource>
<asp:Label ID="Label2" runat="server" Text="Label" Width="258px"></asp:Label><asp:Button
ID="Button1" runat="server" Text="Button" /><asp:Label ID="Label3" runat="server"
Text="Label"></asp:Label>

code--

Protected Sub SqlDataSource3_Selected(ByVal sender As Object, ByVal e As SqlDataSourceStatusEventArgs)

Dim myvalue As Object = e.Command.Parameters("@.userName").Value
Label3.Text = CType(myvalue, String)

End Sub

--code

Within the selectparameter part, you can change the direction property to meet your need.

|||

Thank for the reply! Is it possible to see the code in C#? I don't know VB.

|||

protected void SqlDataSource3_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
object myvalue = e.Command.Parameters("@.userName").Value;
Label3.Text = ((string)(myvalue));
}

By the way, for learning purpose you can use this VB.NET to C# converter to convert some code snippets.

http://www.developerfusion.co.uk/utilities/convertvbtocsharp.aspx

|||

Thanks again for the help but I'm getting the error:

"Parameters is a Property' but is used like a method"

|||

bmanmike39:

Thanks again for the help but I'm getting the error:

"Parameters is a Property' but is used like a method"

C# uses [] brackets for indexers, so it should be:

object myvalue = e.Command.Parameters["@.userName"].Value;

HTH,
Ryan

|||

Now i'm getting the exception : "an sql Parameter with parameter name @.userName is not contained in this sql parameter collection"

Thanks for any help!

sql

Monday, March 19, 2012

Getting results from sqldatasource in codebehind

(New to ASP.net 2.0 and database connection)

I have created an sqldatasource on the aspx page, which works fine, but how do I get the results from it in the codebehind?

hmm..you should create the datasource in the code behind page. I mean that's what the page is for. Place all your asp.net code in it. If you use a code-behind page then aspx page is just for displaying the data.
|||

I can't seem to get it working. The connection works fine (I believe), but I can't seem to give the parameters a value

I have this code: (I know it's Insert instead of select, but that's what I'm working on now)

SqlDataSourceSupplierList.InsertCommand ="INSERT INTO dbo.ProdSup(SupID, ProdID) VALUES (@.SupID, @.ProdID)";

SqlDataSourceSupplierList.InsertParameters.Add("@.SupID", SqlDbType.Int) = 4;

SqlDataSourceSupplierList.InsertParameters.Add("@.ProdID","8");

SqlDataSourceSupplierList.Insert();

As you can see I have tried two ways to give them values, but none of them works. The fields in the DB are both integer, which I guess is why the second try doesn't work (it sends '8' in as a string)... The error I get here is that it "cannot insert the value NULL into column"

The line with @.SupID gives me this error:

CS1502: The best overloaded method match for 'System.Web.UI.WebControls.ParameterCollection.Add(string, string)' has some invalid arguments

What's wrong here?