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

Friday, March 9, 2012

How to Retrive single data from sqldatasource control

hi,

i need to code for retrieving single data from sqldatasource control. i need the full set of coding

connecting
retrieving data in text box
editing data to the table
updating data to the table
deleting data to the table

i want to fetch "single field data"

any one who know the code please post reply or send it to my mail senthilonline_foryou@.rediffmail.comI suggest that you use a stored procedure like this (assuming ID is an identity index column, with a data row NAME VARCHAR(50) in Table Fred)

CREATE PROCEDURE dbo.uspGetFred
(
@.ID INT,
@.NAME VARCHAR(50) OUTPUT
)
SET NOCOUNT ON
SELECT NAME FROM Fred WHERE ID = @.ID
GO

The VB code below retrieves NAME into aName fpor a given value of iID
CONST DBCONNECT As String = "Your Connect String"

Dim sName As String = ""
Dim xSqlConnection As SqlConnection = New SqlConnection(DBCONNECT )
Dim xSqlCommand As SqlCommand = New SqlCommand("uspGetFred", xSqlConnection)
Try
xSqlCommand.CommandType = CommandType.StoredProcedure
xSqlCommand.Parameters.Add("@.ID", SqlDbType.Int)
xSqlCommand.Parameters("@.ID").Value = CType(iId, Integer)
xSqlCommand.Parameters.Add("@.NAME", SqlDbType.VarChar, 50)
xSqlCommand.Parameters("@.NAME").Direction = ParameterDirection.Output
xSqlCommand.Connection.Open()
xSqlCommand.ExecuteNonQuery()
sName = xSqlCommand.Parameters("@.NAME").Value
Catch ex As Exception
' Handle your error here!
Finally
xSqlCommand.Connection.Close()
xSqlCommand.Dispose()
xSqlConnection.Dispose()
End Try

HTH!Idea

Friday, February 24, 2012

how to retrieve datas from a SqlDataSource

Hi! I'm a novice in asp .net

I've a SqlDataSource component on an Aspx page.
In the associated C# file, I would like to use datas from the query stored in the SqlDataSource component.

How to do this?

Thanxs :)

An example

<%@.PageLanguage="C#" %>

<%@.ImportNamespace="System.Data" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<scriptrunat="server">

protected void Page_Load(object sender, EventArgs e)

{

DataView dv = (DataView)SqlDataSource1.Select(new DataSourceSelectArguments());

DataTable dt = dv.Table;

// display table

bool pagesToDo = true;

int index = 0;

while (pagesToDo)

{

Table t = GetDisplayTable(dt);

t.CssClass = "PageBreakStyle";

Controls.Add(t);

int nextPageEndsAt = index + 10;

while (index < nextPageEndsAt && pagesToDo)

{

TableRow tr = new TableRow();

t.Rows.Add(tr);

foreach (DataColumn dc in dt.Columns)

{

TableCell tc = new TableCell();

tr.Cells.Add(tc);

tc.Text = dt.Rows[index][dc.ColumnName].ToString();

}

index++;

if (index == dt.Rows.Count)

{

pagesToDo = false;

break;

}

}

}

}

Table GetDisplayTable(DataTable dt)

{

Table t =newTable();

TableHeaderRow thr =newTableHeaderRow();

t.Rows.Add(thr);

foreach (DataColumn dcin dt.Columns)

{

TableHeaderCell thc =newTableHeaderCell();

thc.Text = dc.ColumnName;

thr.Cells.Add(thc);

}

return t;

}

</script>

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

<title>Untitled Page</title>

<styletype="text/css">

.PageBreakStyle

{

page-break-after:always;

}

</style>

</head>

<body>

<formid="form1"runat="server">

<asp:SqlDataSourceID="SqlDataSource1"runat="server"ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"

SelectCommand="SELECT [ProductID], [ProductName] FROM [Products]"></asp:SqlDataSource>

</form>

</body>

</html>

|||

Thanks, it works!

very cool man ^^

How to retrieve data from sqldatasource?

Okay, I used the SQLDataSource control to get my data from the databasetable. What or how do I retrieve individual data from thesqldatasource? I want to do some string comparison and manipulationbefore I display it to the browser. How can this be accomplish?

Help is appreciated.

Hi,

The SqlDataSource control designed for data bound controls so you can't access data except by data bound control, for example if your using gridview you can access data item by handle RowDataBound event and make your changes there

I hope this help.

|||

If your DataSourceMode of your SQLDataSource stays as default which is DataSet, you can retrieve a dataview object of your SQLDataSource. If DataSourceMode="DataReader" in yourSQLDataSource, you can retrieve a datareader object.

Here is an example for dataview:

'DataView
Dim mydataview As System.Data.DataView =CType(SQLDataSource1.Select(DataSourceSelectArguments.Empty), System.Data.DataView)

For Each dr As DataRow In dv.Table.Rows
...

Next

'For a Datareader

Dim myreader as System.Data.SqlClient.SqlDataReader = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), System.Data.SqlClient.SqlDataReader)

While myreader.reader

...

End While

|||Many thanks for the response. Limno, I will try that. In the mean time,if SQLDataSource is for databound only control then what do I need todo so that I can grab the individual field of my table and do datacomparison and then present it on the web?|||

Hi,

It is a way you can access your datasource programmatically.

This link will give a little more information on this topic.http://aspnet.4guysfromrolla.com/articles/022206-1.aspx

|||Okay, here's what I have.

<asp:SqlDataSource ID="sqlEnewsCate" runat="server" ConnectionString="<%$ ConnectionStrings:myConnectionString%>"
SelectCommand="SELECT * FROM [enewscate] WHERE ([id_ecate] = @.id_ecate) ORDER BY [order_ecate]">
<SelectParameters>
<asp:QueryStringParameter Name="id_ecate" QueryStringField="id" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="sqlEnews" runat="server" ConnectionString="<%$ ConnectionStrings:myConnectionString%>"
SelectCommand="SELECT * FROM [enews] WHERE ([idmnu_nws] = @.idmnu_nws)">
<SelectParameters>
<asp:QueryStringParameter Name="idmnu_nws" QueryStringField="id" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
And here is my code behind in the Page Load:
protected void Page_Load(object sender, EventArgs e)
{
string newsID;
string nwsStory ="";
newsID = Request.QueryString["id"];

if (newsID =="")
{
Response.Redirect("Default.aspx?id=3");
}

if (Request.QueryString["stry"] =="" || Request.QueryString["stry"] ==null)
{
nwsStory ="";
}
OleDbDataReader newsReader = (OleDbDataReader)sqlEnews.Select(DataSourceSelectArguments.Empty);
if (newsReader.Read())
{
if (nwsStory =="" || nwsStory ==null)
{
OleDbDataReader reader = (OleDbDataReader)sqlEnewsCate.Select(DataSourceSelectArguments.Empty);
if (reader.Read())
{
string pic = Convert.ToString(reader["sidePic_ecate"]);
if (pic =="" || pic ==null)
{
imgArticle.ImageUrl ="images/11.jpg";
}
else
{
imgArticle.ImageUrl ="images/" + pic;
}
reader.Close();
}
}
else if (nwsStory =="full")
{
string pic = Convert.ToString(newsReader["sidePic_nws"]);
if (pic =="" || pic ==null)
{
imgArticle.ImageUrl ="images/11.jpg";
}
else
{
imgArticle.ImageUrl ="images/" + pic;
}
}
newsReader.Close();
}
}

And here is the error I received:

erver Error in '/Alumni' Application.

Object reference not set to an instance of an object.

Description:Anunhandled exception occurred during the execution of the current webrequest. Please review the stack trace for more information about theerror and where it originated in the code.

Exception Details:System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 29: }
Line 30: OleDbDataReader newsReader = (OleDbDataReader)sqlEnews.Select(DataSourceSelectArguments.Empty);
Line 31: if (newsReader.Read())
Line 32: {
Line 33: if (nwsStory == "" || nwsStory == null)


Source File: e:\wwwroot\home\mySite\enews\Default.aspx.cs Line: 31

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
enews_Default.Page_Load(Object sender, EventArgs e) in e:\wwwroot\home\mySite\enews\Default.aspx.cs:31
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +34
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +47
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061



Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.42|||

If your DataSourceMode of your SQLDataSource stays as default which is DataSet, you can retrieve a dataview object of your SQLDataSource. If DataSourceMode="DataReader" in yourSQLDataSource, you can retrieve a datareader object.

You need add this to your datasource:

DataSourceMode="DataReader"

|||Thanks for the immediate response. Where in the do I put DataSourceMode="DataReader" in?|||<asp:SqlDataSource ID="sqlEnewsCate" runat="server"DataSourceMode="DataReader" .....|||Thanks! I'll give that a try.|||I still received the same error.|||

You need this in the top of your code behind page too:

using System.Data.OleDb

|||I do have that. I downloaded the source code from the link you gave me.|||

OleDbDataReader newsReader = (OleDbDataReader)sqlEnews.Select(DataSourceSelectArguments.Empty);

and this one:

OleDbDataReader newsReader = (OleDbDataReader)sqlEnewsCate.Select(DataSourceSelectArguments.Empty);

Can you see the problem?

|||Thanks for the response. If you look at my code above, you'll see thatI have both those lines in my code. Unless I did it wrong somehow.

how to retrieve data from sqldatasource to textbox

my problem is i can't retrieve data from my sqldatasource to be displayed in textbox... i try to do it in vb codes. somebody help me here?

Hi firefox3000,

First i would suggest you posting your code here so we can better help you.

And second, what do you mean by "can't retrieve data from my sqldatasource to be displayed in textbox". Do you mean you cannot retrieve data from sqldatasource OR you can get the data but you cannot get them dispalyed? Easiest way is to set up a break point after retrieving data though database query and see if the data has been populated.

If you cannot get the data, tryado.net stuff and if cannot get those data displayed, check if you have bound your textbox.text property to a wrong place.

Hope my suggestion helps

|||

Hello Bo Chen,

I think I can't retrieve my data from my sqldatasource. Pls check my code:

Imports SystemImports System.DataImports System.ConfigurationImports System.WebImports System.Web.SecurityImports System.Web.UIImports System.Web.UI.WebControlsImports System.Web.UI.WebControls.WebPartsImports System.Web.UI.HtmlControlsImports Telerik.WebControlsImports System.Data.SqlClientImports Telerik.WebControls.GridEditFormItemImports System.Data.SqlTypesPartialClass _DefaultInherits System.Web.UI.PagePublic Shared dtTableAs New DataTablePublic sqlConnectionAs New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ToString())Public sqlAdapterAs New SqlDataAdapter()Public sqlCommandAs New SqlCommand()Protected Sub RadGrid1_NeedDataSource(ByVal sourceAs Object,ByVal eAs Telerik.WebControls.GridNeedDataSourceEventArgs)Handles RadGrid1.NeedDataSource sqlConnection.Open()Dim queryAs String ="SELECT * FROM blogpost" sqlAdapter.SelectCommand =New SqlCommand(query, sqlConnection) sqlAdapter.Fill(dtTable) RadGrid1.DataSource = dtTable sqlConnection.Close()End Sub Protected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.Load'Dim txt As Label 'For Each item As GridDataItem In RadGrid1.Items 'txt = CType(Item("TemplateColumn").FindControl("Label1"), Label) 'MsgBox(txt.Text) 'Next 'Dim txt As Label = CType(RadGrid1.Items.Item("TemplateColumn").FindControl("Label1"), Label)End Sub Protected Sub RadGrid1_ItemDataBound(ByVal senderAs Object,ByVal eAs Telerik.WebControls.GridItemEventArgs)Handles RadGrid1.ItemDataBound'If TypeOf e.Item Is GridDataItem Then 'Dim dataitem As GridDataItem = TryCast(e.Item, GridDataItem) 'Find the control in the template column using the find control method 'Dim TextBox1 As Label = DirectCast(dataitem("TemplateColumn").FindControl("Label1"), Label) 'MsgBox(TextBox1.Text) 'End If sqlConnection.Open()Dim queryAs String ="SELECT * FROM blogpost" sqlAdapter.SelectCommand =New SqlCommand(query, sqlConnection) sqlAdapter.Fill(dtTable)Dim userControlAs UserControl = TryCast(e.Item.FindControl(GridEditFormItem.EditFormUserControlID), UserControl)If TypeOf e.ItemIs GridDataItemThen Dim dataItemAs GridDataItem = TryCast(e.Item, GridDataItem)Dim lblDateTimeAs Label =CType(dataItem.FindControl("Label1"), Label)Dim divContentAs HtmlGenericControl =CType(dataItem.FindControl("blog"), HtmlGenericControl)Dim lblPostedByAs Label =CType(dataItem.FindControl("Label2"), Label) lblDateTime.Text = dtTable'''' I dont know how to do it here....End If sqlConnection.Close()End SubEnd Class
|||

Hi firefox3000,

Sorry i didn't know your talbe structure so i cannot give you an accurate answer.

Your code should look like this:

lblDateTime.Text = dtTable'''' I dont know how to do it here....

lblDataTime.Text=dtTable[rownumber][colnumber].ToString();

Any further issues, please let me know. thanks

|||

Hi Bo Chen,

In rownumber or colnumber, can i make it a name of my field in my table?

table:

id - int

title - varchar

blog - varchar

datetime - datetime

lblDateTime.Text = dtTable(0)("title")
is that possible? 

How to retrieve data from a SQLDataSource control

I have made a SQLDataSource control with the select command:

SELECT COUNT(*) AS 'Antall' FROM Utgivelse WHERE (medieID = @.medieID)

I want to use the "Antall" result programmatically in C# code. I try the following statement:

IDataReader MyReader;

MyReader = CType(SqlDataSource2.Select(DataSourceSelectArguments.Empty),IDataReader);

but it doesnot work. Can somebody help me how to get the data from th control ?

Tom

What do you mean by "it does not work"? Do you get an error message? If so, what is it? Also, what database are you accessing? SQL Server? Access? Did you set the mode of the DataSource to DataReader or leave it as the default DataSet?

Have a look at this:http://www.mikesdotnetting.com/Article.aspx?ArticleID=45

Finally, are you using the result from the datasource for any other purpose? If not, you would be better using plain ADO.NET code and ExecuteScalar() for a Count result. If you are binding the result to a control, it would be simpler to read the value from the control once it has been bound.

|||

I got the answer of my problem i the URL you gave me. My working code:

DataView dvSql = (DataView)SqlDataSource2.Select(DataSourceSelectArguments.Empty);

int result;foreach (DataRowView drvSqlin dvSql)

{

result = (int)drvSql["antall"];

if (result > 0)

Label1.Text ="The record is in use and can not be deleted";

Thank a lot for your help !!!

Tom

how to retriece single record in database by using SqlDataSource??

Is me again,and now i facing problem to retrieve a single record from the database.

here is my code:

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim user As String
user = TextBox1.Text
Dim varpassword
Dim mydata As SqlDataSource

mydata.SelectCommand = "Select * from tbluser where uLogin = '" & user & "'"
varpassword = mydata.SelectCommand.uPassword

End Sub
End Class

but i get the error : 'uPassword' is not a member of 'String'

i wan to retrieve the password of that user,can anyone help me?

thanksSmile

First create a select parameter "uPassword" of type "String".

|||

Girijesh:

First create a select parameter "uPassword" of type "String".

i not really understand about creating the select parameter.

can u write the line of code for me?thanksSmile

|||

Hi there,

Use this:

imports System.Data.Sql

Dim dt as new DataTable

Dim query As String = "Select * from tbluser where uLogin = '" & user & "'"

Dim conn as new SqlConnection(connection)

Dim adapter as new SqlDataAdapter

adapter.SelectCommand =new SqlCommand(query, conn);
adapter.Fill(dt);

// this DataTable only has one row, the one for this username

Dim password As String = dt.rows(0)("uPassword")

hope it helps you out,

gonzzas