Quantcast
Channel: DataSource Controls - SqlDataSource, ObjectDataSource, etc.
Viewing all 956 articles
Browse latest View live

Objectdatasource feeding RDLC. Error when Objectdatasource returns nothing. An error has occurred during report processing. cannot create a datareader for dataset

$
0
0

Hi,

I have an objectdatasource connecting to a wcf service which calls a stored procedure for some results. When the query returns nothing, the RDLC dataset which is associating with the ObjectDatasource throws an error during the RDLC processing.

"An error has occurred during report processing.  cannot create a datareader for dataset"

How should it be handled? Please advise.


sql express problem

$
0
0

I have a sql express database runs fine on one server (2008), then I moved the entire website including the sql express file to another machine (also 2008). I created asp.net 4.0 in the application pool and used the windows network service account.  I also set appropriate file permissions for network service to the sql express file. Everything worked fine for a while, then for some reason I cannot access the database.  I did something more, trying to fix it, basically, remove and recreate the entries in the application pools.  Now, I just cannot make it work.  The error message I get is "404 file or directory cannot be found" if I enable asp.net 4.0 class. 

If using ASP.NET v4.0 integrated, I got 

CREATE DATABASE permission denied in database 'master'.
An attempt to attach an auto-named database for file D:\inetpub\wwwroot\App_Data\RefSchedule.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

Access a strongly typed dataset Guid column gives exception

$
0
0

Hi,

When accessing a strongly typed dataset column which is a Guid type and can have a DBnull value, I always get a null exception in asp.net. I tried changing the property of the dataset column to not throw exception when this column is null, VS2005 won't let me do it. It said a Guid column in dataset will always throw exception.

How can I access this column to compare for a DBNull value. My code depends on this column's Null value and will perform different logic.

 

ConnectionString property has not been initialized.

$
0
0

This is my webconfig file

<?xml version="1.0"?>

<configuration>


<connectionStrings>
<add
name="TBNETConnectionString"
connectionString="Data Source=localhost\SQLEXPRESS;Initial
Catalog=NET;Persist Security Info=True;User
ID=sa;Password=sa"
providerName="System.Data.SqlClient"
/>
</connectionStrings>

<system.web>
<compilation debug="true" targetFramework="4.0" />


</system.web>
</configuration>

This is my default.aspx.cs file

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.SqlClient;


public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["SearchString"] != null)
{
DisplaySearchResults(Request.QueryString["SearchString"]);
}
}

public void DisplaySearchResults(string strSearch)
{
SqlCommand cmd = new SqlCommand("SearchByString", new SqlConnection(ConfigurationManager.AppSettings["NETConnectionstring"]));
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SearchString", strSearch);
cmd.Connection.Open();
Repeater1.DataSource = cmd.ExecuteReader();
Repeater1.DataBind();
cmd.Connection.Close();
cmd.Connection.Dispose();
}


protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text == "" | TextBox1.Text == null)
{
lblStatus.Text = "Please enter valid search criteria";
}
else
{
DisplaySearchResults(TextBox1.Text);
lblStatus.Text = "";
TextBox1.Text = "Request Submitted...";
}


}
}

gives InvalidOperationException was unhandled by user code

ConnectionString property has not been initialized.

What is the error and how to solve it??

Keep track changes made in data

$
0
0

I want to create a page(using GridView) where it will detect changes made in the database and display it for Administrator observation. I've created a table name history for this purpose.

History

guid (uniqueidentifier)

dateCreated(datetime)

lastDateUpdated(datetime)

changesMade(varchar(50))  ---- eg; dropdownlist

oldValue(varchar(50))  ----- compaq

newValue(varchar(50)) -----dell

updateBy(varchar(10)) <------ username of registered user

comNo(int) = foreign key for Computer table

History data will insert data whenever a changes made. Could anyone advise and direct me how to do this function. I was thinking of using stored procedure to insert the data. Thanks in advance.

syntax for "LIKE" in parameterized query

$
0
0

Hi All: I have a datatable in a dataset that I want to add a LIKE query to, but I can't seem to get the syntax right.

I'm trying 

SELECT  lastName
FROM   members
WHERE  lastName LIKE  @lname + '%'

but it's not returning any results unless I enter the full name...what am I missing?

I also tried

WHERE  lastName LIKE  (@lname + '%')

and

WHERE  lastName LIKE ('' + @lname + '%')

How to import an mdf file into SQL Server Management Studio Express?

$
0
0

Hi

I had to recover my computer but before I did that I grabbed a new version of my mdf file but I don't know how to actually import it into SQL Server Management Studio Express evertime I try to open the file up it just crashes.

 I rather not have to redue that whole database again. I am a noob so step by step instructions are needed.

 

Thanks
 

For each loop in a stored procedure/ T-SQL

$
0
0

I want to create a stored procedure in a sql server agent job to run the routine every 24 hours. 

I have 5 tables here.

table1 - species list

SpeciesID Name

1             Salmon

2             Trout

3             Seabass

............

Table2 - Countries list

CountryID   Country

1                UK

2                 USA

3                 Germany

..................

Table3 - Type list

TypeID  Type

1          SD112

2          SL529

..........

Table4 - Data

ID  SpeciesID   CountryID  TypeID  Value  CreatedDate

1       1               1               1       89.5        01/01/2014 1:00

2       1                1               1      85.2        01/01/2014 1:05

3       1                1               1      84.1        01/01/2014 1:10

4       2                1              1       79           01/01/2014 1:15

.............

Table 5 - Average Value of the Data

ID  SpeciesID  CountryID    TypeID  AvgValue   MinValue  MaxValue CreatedDate

1       1               1                1            86.26         84.1              89.5         02/01/2014 00:00

2       2               1               1           79            ...................................................................

................................................

For Table5, I want to created a stored procedure that inserts average, Min and Max data for different species, country and type from table4.

Plz help. Thank you.


entity data source updating event problem?

$
0
0

Hi friends i have an edmx file where there is entity called TransferDetails which has the Following fields in it: Customer Name,CustomerID,CustomerSales,UserLogin

I am using a rad grid that shows the entiy data via ana enity data source : Customer_EDS.

 So the fields Customer Name,CustomerID,CustomerSales are inserted ,updated via the radgrid and Customer_EDS.  BUt the userlogin field is the field which conatins the user who makes the data record changes. This is my code i am trying to the update the UserLogin field but does not seem to work..Please some one guide me on this as to what i am missing here

protected void Customer_EDS_Updating(object sender, EntityDataSourceChangingEventArgs e)
        {

            lblUser_Login.Text = User.Identity.Name;
            using (FieldEquipmentEntities  dataEntity = new FieldEquipmentEntities())
            {
                TransferDetail tfdetail = new TransferDetail();

                tfdetail.User_Login = User.Identity.Name.ToString();

                dataEntity.SaveChanges();

                
            }



        }

FilterParameters with DropDownList and TextBox

$
0
0

Hello,

I have a filtered GridView thanks to some DropDownList and a TextBox.

I put the autopostback to true for DropDownList to filter the GridView and I have a textBox and a button to filter the content of the GridView.

The problem is : when I search something with a TextBox, it works fine. But if I just want to use DropDownList to filter the GridView (and not the TextBox), it doesn't works.

The SQLDatasource code and the filtered GirdView to better understand :

<asp:GridView ID="GridView1" Width="100%" Height="100%" HeaderStyle-BackColor="#e80616"
                    HeaderStyle-ForeColor="White" runat="server" AutoGenerateColumns="false" DataSourceID="GridDataSource"
                    ShowHeader="true"><Columns><asp:BoundField DataField="ObjectifStrategique" HeaderText="Objectif stratégique"
                            ItemStyle-Width="120" ItemStyle-HorizontalAlign="Left" HtmlEncode="false" /><asp:BoundField DataField="ObjectifOperationnel" HeaderText="Objectif Opérationnel"
                            ItemStyle-Width="120" ItemStyle-HorizontalAlign="Left" HtmlEncode="false" /><asp:BoundField DataField="RefAct" HeaderText="Réf.Activité" ItemStyle-Width="30px"
                            ItemStyle-HorizontalAlign="Left" HtmlEncode="false" /><asp:BoundField DataField="DescriptionActivite" HeaderText="Description activité"
                            ItemStyle-Width="180" ItemStyle-HorizontalAlign="Left" HtmlEncode="false" /><asp:BoundField DataField="Debut" HeaderText="Début" ItemStyle-Width="30px" HtmlEncode="false" /><asp:BoundField DataField="Fin" HeaderText="Fin" ItemStyle-Width="30px" HtmlEncode="false" /><asp:BoundField DataField="Nom" HeaderText="Chef de file" ItemStyle-Width="120" ItemStyle-HorizontalAlign="Left"
                            HtmlEncode="false" /><asp:BoundField DataField="Livrables" HeaderText="Livrables" ItemStyle-Width="120"
                            ItemStyle-HorizontalAlign="Left" HtmlEncode="false" /></Columns></asp:GridView>
<asp:SqlDataSource ID="GridDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:connexionBase %>"
                SelectCommand="SELECT [Nom], [RefAct], [Entite], [Origine], [ObjectifStrategique], [Cle], [MAP], [SNS], [ObjectifOperationnel], [DescriptionActivite], [Debut], [Fin], [Livrables], [Annee], [ID] FROM reponse"
                FilterExpression="Nom like '%{0}%' AND Entite like '%{1}%' AND Origine like '%{2}%' AND ObjectifStrategique like '%{3}%' AND Cle like '%{4}%' AND MAP like '%{5}%' AND SNS like '%{6}%' AND Annee = {7} AND RefAct LIKE '%{8}%'"><FilterParameters><asp:ControlParameter Name="Nom" ControlID="NomPersonne" PropertyName="SelectedValue"
                        ConvertEmptyStringToNull="false" /><asp:ControlParameter Name="Entite" ControlID="NomEntite" PropertyName="SelectedValue"
                        ConvertEmptyStringToNull="false" /><asp:ControlParameter Name="Origine" ControlID="ContenuOrigine" PropertyName="SelectedValue"
                        ConvertEmptyStringToNull="false" /><asp:ControlParameter Name="ObjectifStrategique" ControlID="Objectif_strategique"
                        PropertyName="SelectedValue" ConvertEmptyStringToNull="false" /><asp:ControlParameter Name="Cle" ControlID="Key" PropertyName="SelectedValue" ConvertEmptyStringToNull="false" /><asp:ControlParameter Name="MAP" ControlID="map1" PropertyName="SelectedValue" ConvertEmptyStringToNull="false" /><asp:ControlParameter Name="SNS" ControlID="sns1" PropertyName="SelectedValue" ConvertEmptyStringToNull="false" /><asp:ControlParameter Name="Annee" ControlID="year" PropertyName="SelectedValue"
                        ConvertEmptyStringToNull="false" /><asp:ControlParameter Name="RefAct" ControlID="txtSearch" PropertyName="Text" /></FilterParameters></asp:SqlDataSource>

Thanks for your help !

Sqlexception was unhandled by user code

$
0
0

I am creating a website in which i have a created a user registration form.

I created a procedure name registration and a table with name tblregistration.

Following is my code which is giving error sqlexception was unhandled by user code(Invalid object name registration)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void RegisterUser(object sender, EventArgs e)
{
int Username = 0;
string constr = ConfigurationManager.ConnectionStrings["TBNETConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Registration"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())

{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("@Password", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("@Email", TextBox3.Text.Trim());
cmd.Connection = con;
con.Open();
Username = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
}
string message = string.Empty;
switch (Username)
{
case -1:
message = "Username already exists.\\nPlease choose a different username.";
break;
case -2:
message = "Supplied email address has already been used.";
break;
default:
message = "Registration successful.\\nUser Id: " + Username.ToString();
break;
}
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
}
}

}

What could be the possible error???

Get Eval in code behind

$
0
0

Hi?

I got struck at one point. Can any tell me how we can get Eval value from gridview in codebehind.

<asp:TemplateField HeaderText="Task Name" HeaderStyle-Width="200px" ItemStyle-Width="200px">                                                            <ItemTemplate>
<%#Eval("taskInfo") %>
</ItemTemplate>
</asp:TemplateField>

I need <%#Eval("taskInfo")%> value in codebehind.. how?

How to create Search_btn in Masterpage without Gridview

$
0
0

Hello,

Im trying to create Textbox and button for Search in my Masterpage between my MenuList. 

When i clicked my Search_button its takes me to the masterPage.aspx.cs and then there I have this code under 

Response.Redirect("Find.aspx")...

So I have create my Design (textbox and button) in my masterpage.. 

And when I create a dataGrid in masterpage then my MenuList i changes. How can I write code without dataGrid?

Like then I search Username and clicked search button on my masterpage it will show users in my contentpage?

In Find.aspx.cs there is a that line shows

protected void Page_load(object sender, EventArgs e)

{

??//I have no idea

}

thanks 

sqldatasource and check if any return

$
0
0

Hi,

I want to check if the below sqldatasource has any return values in my function i.e. I don't want to return any rows just check whether it is null or not.

I looked online and seen a way of doing this in the onselecting part of the datasource but I am just looking to check from a normal function.

How can I do this?

Thanks for any help.

 

Comments_DataSource.SelectParameters("ID").DefaultValue = ID1 

What to pass in UpdateParameter of SqlDataSource?

$
0
0

Below is my Gridview

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
        AllowSorting="True" AutoGenerateColumns="False"  DataSourceID="DataSource1"><Columns><asp:CommandField ShowDeleteButton="True" ShowEditButton="True" /><asp:BoundField DataField="id1" HeaderText="id1" ReadOnly="True" Visible="false"/><asp:BoundField DataField="fn" HeaderText="first name" ReadOnly="False"/><asp:BoundField DataField="add" HeaderText="address" InsertVisible="False" ReadOnly="False"/></Columns></asp:GridView>

Below are the two stored procedure which I am using in SQL data source.

alter procedure dbo.sp_select
As
Begin
  Select id1, fn, add from table1
End

alter procedure dbo.sp_update
  @TableID as int,
  @FirstName as varchar(50),
  @Address as varchar(50) 	
As
Begin
  update table1 set fn = @FirstName
		    add = @Address
  Where	id1 = @TableID
End


In sp_select stored procedure, I am fetching orginal name from the table but in sp_update stored proceduire, it is accepting some other name as variable so Please suggest me that which parameter to pass in update parameter so it should work. Refer below the sql data source

<asp:SqlDataSource ID="DataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:connstr1 %>" 
                        SelectCommand="sp_select" SelectCommandType="StoredProcedure"
                        UpdateCommand="sp_update" UpdateCommandType="StoredProcedure"><SelectParameters><asp:SessionParameter DefaultValue="null" Name="vUserId" SessionField="UserName"/></SelectParameters><UpdateParameters><asp:SessionParameter DefaultValue="null" Name="vUserId" SessionField="UserName"/><asp:ControlParameter Name="vCommID" ControlId="GridView1"/><asp:ControlParameter Name="vCommDetail" ControlId="GridView1"/></UpdateParameters>


Adding Parameters to ObjectDataSource?

$
0
0

Hi all, I have an objectdatasource that I need to add a parameter to.  The parameter should be pulled from a Checkbox on the page with an ID of CheckBox_SearchAllSites.  How would I do this?  Below is what I tried!

ASP:

<asp:ObjectDataSource runat="server" ID="ObjectDataSource_Employee"
DataObjectTypeName="EnvirocorFacilityManagement.Database.Employee"
SelectMethod="GetEmployeesDataSet"
TypeName="EnvirocorFacilityManagement.Database.EmployeeDB"
ConvertNullToDBNull="True" DeleteMethod="DeleteEmployee"
InsertMethod="InsertEmployee" OldValuesParameterFormatString="original_{0}"
UpdateMethod="UpdateEmployee">
<SelectParameters>
<asp:ControlParameter ControlID ="CheckBox_SelectAllSites" Type="Boolean" Name="includeAllSites" DefaultValue="false" />
</SelectParameters>
</asp:ObjectDataSource>

c# Code:

public DataSet GetEmployeesDataSet(bool includeAllSites)
{
return (DataSet)GetEmployees(null, true, includeAllSites);
}

Pass multiple parameter to stored procedure?

$
0
0

Hello

Need to pass multiple parameter to my stored procedure. 

<asp:SqlDataSource ID="sqlDataSourceGridView" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        SelectCommand="GetAllLots" SelectCommandType="StoredProcedure"
            OnSelecting="sqlDataSourceGridView_Selecting"><SelectParameters><asp:Parameter Name="Category"  DefaultValue="1"/><asp:Parameter Name="Status" DefaultValue="2" /><asp:Parameter Name="LotIDs" /> //How can i pass this selected values to stored procedure?<asp:Parameter Name="ShapeIDs" /> //How can i pass this selected values to stored procedure?<asp:Parameter Name="Operation" DefaultValue="0" /></SelectParameters></asp:SqlDataSource>

Defined NVARCHAR LotIds and ShapeIds in my stored procedure and tested with Management studio.

When i pass values manually to stored procedure, working good but if trying to fetch data with sqldatasource (with stored procedure) no results. 

Any help?

Data Convertion

$
0
0

Hello guys, this is my first time here as a member.

I'm facing a problem now with my application, in which I want to search in a MS-SQL DB, through a select storage procedure, some informations from a table.

The problem is: In the Asp.Net app, when I try to use the Datasource Form Parameter to filter 2 dates, there is a different date format between the MS-SQL and the input box (with JS) which I am using, so I can't filter anything.

Do you have an ideia on how should I do it? Should execute the procedure through C# coding?

App format: dd/MM/yyyy

MS-SQL format: yyyy-MM-dd

<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:connectionStr %>" SelectCommand="SP_SEARCH" SelectCommandType="StoredProcedure"><SelectParameters><asp:FormParameter DefaultValue="01/01/2014" FormField="datepick" Name="date1" Type="DateTime" /><asp:FormParameter DefaultValue="01/01/2015" FormField="datepick2" Name="date2" Type="DateTime" /></SelectParameters></asp:SqlDataSource>

How to implement update function!

$
0
0

The following is some info that I received from an earlier post!(Mikes.Nett) Can someone help me to revise this code so that I can connect to my database. I am limited in my understanding of how to make this savePersonell method interact with the information that I am trying to access! The use of ids is something that I am not familair with so I need help to build my base of knowledge on this subject. Should I be intializing  save personell data with numbers to index the ids, and if so can you explain how this should be done??? Thanks, Markus33

(Mikes.Nett) Your data layer has some basic mistakes. You should be using parameters instead of concatenating variables directly into a SQL statement. Also, you should use @@Identity to get the most recently created record - not MAX(Id). Also, why are you inserting a record and then updating it? You can do the whole thing with one insert.

Here's a revised version that uses parameters and also takes an additional argument - a nullable int representing the ID of the record to be "saved". If you are updating an existing record, you pass a value in for hte int and the UPDATE statement is executed. If you are creating a new record, you pass null in and the INSERT statement is executed instead. Mikes.net

publicstaticboolSavePersonnel(stringDatabase,stringFirstName,stringLastName,stringPayRate,stringStartDate,stringEndDate,int?Id){try{using(OleDbConnection conn =newOleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source="+Database)){
	    conn.Open();OleDbCommand command = conn.CreateCommand();
            command.Parameters.AddWithValue("FirstName",FirstName);
            command.Parameters.AddWithValue("LastName",LastName);
            command.Parameters.AddWithValue("PayRate",PayRate);
            command.Parameters.AddWithValue("StartDate",StartDate);
            command.Parameters.AddWithValue("EndDate",EndDate);string strSQL;if(!Id.HasValue)// inserting a new record{
                strSQL ="Insert into tblPersonnel (FirstName, LastName, PayRate, StartDate, EndDate) values (?,?,?,?,?)";}else// updating existing record{
                strSQL ="Update tblPersonnel Set FirstName = ?, LastName = ?, PayRate = ?, StartDate = ?, EndDate = ? Where ID = ?";
                command.Parameters.AddWithValue("ID", ID);}
            command.CommandText= strSQL;
            command.ExecuteNonQuery();returntrue;}}catch(Exception ex){returnfalse;}}

How do I configurate a calendar on ASP.NET in C# with SQL?

$
0
0

Hi, I'm glad to join this forum Big Grin | :-D 
 
I've a few questions...
 
I'm learning ASP.NET and C# and I've a project in which I've to make a management system of work employed.
 
I want to make a calendar in which workpeople need to select days and specify the work that they have done every hour.
 
My idea is click on days, and show a menu with all the hours and a dropdown with the types of work that I've registered on my SQL database.
 
If a day hasn't been filled, it will be red, if it's incomplete yellow, and if it's completely filled with all the hours, in green.
 
Every employer has his own login session, and have to fill the management system.
 
I know that it's a little bit complicated, I don't know much at programming and my english isn't very well, but If you know how to arrange me, or how to make this, I will be very grateful.
 
It's not neccesary to explain step by step where I have to click, but I need to know how it's made and which properties, controls and features I've to use.
 
Thank all of you!

Viewing all 956 articles
Browse latest View live


Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>