Stored procedure doesnt return any value - asp.net

I got simple problem but I got no idea about where is problem :/ So in my GridView I am using ObjectDataSource with custom paging like in this tutorial http://www.codedigest.com/Articles/ASPNET/180_Custom_GridView_Paging_with_ObjectDataSource_Control_with_ASPNet_20.aspx
Here is my aspx markup:
<asp:ObjectDataSource ID="ObjectDataSource2"
runat="server"
onselecting="ObjectDataSource2_Selecting"
EnablePaging="true"
SelectCountMethod="GetItemsCount"
SelectMethod="BindItems"
StartRowIndexParameterName="startRowIndex"
MaximumRowsParameterName="maximumRows"
TypeName="eSova.Utilities.RecordUtilities"
>
And method which calling:
public static DataTable BindItems(int category,int search,int startRowIndex,int maximumRows)
{
DataTable table = new DataTable();
using (SqlConnection connection = new SqlConnection())
{
ConnectionUtilities.OpenConnection(connection);
SqlTransaction transaction = connection.BeginTransaction();
try
{
SqlCommand command = new SqlCommand("GetItems",connection,transaction);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#RowIndex", SqlDbType.Int, 4).Value = startRowIndex;
command.Parameters.Add("#MaxRows", SqlDbType.Int, 4).Value = maximumRows;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(table);
transaction.Commit();
}
catch
{
transaction.Rollback();
}
}
return table;
}
My stored procedure works just fine and return in all items from table.
But when I analyze the code, I got breakpoint on return and table variable is without records. I don't know where is problem.
UPDATE:
create proc [dbo].[GetItems](#RowIndex int,#MaxRows int)
as
declare #StartRows int
declare #EndRow int
set #StartRows=(#RowIndex+1)
set #EndRow=(#StartRows+#MaxRows)
select *
from ( select id, name, filepath, descript, itemlanguage,
filetypeid, ROW_NUMBER() over (ORDER by id)as row FROM Items)as NumberesItems
where row between #StartRows and #EndRow

Your connectionstring is empty.

Related

Procedure or function 'spCategory1' expects parameter '#Cat1ID', which was not supplied

I have two dropdownlists for category and subcategory.So when i change the category,it should populate the subcategory with a desired options depending upon the selection.So obviously i have two tables,one for category and another for subcategory and they are properly linked.Here are the two tables:
create table tblCategory
(
CatId int primary key identity,
Category nvarchar(50)
)
and
create table tblSubCategory
(
SubId int primary key identity,
SubCategory nvarchar(50),
CatId int
)
I have a stored procedure:
create proc spCategory1
#Cat1ID int
as
begin
select * from tblSubCategory where CatId=#Cat1ID
end
The code-behind:
protected void ddlCat1_SelectedIndexChanged(object sender, EventArgs e)
{
int Cat1ID = Convert.ToInt32(ddlCat1.SelectedValue);
string CS = ConfigurationManager.ConnectionStrings["IndiaLystConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spCategory1", con);
cmd.Parameters.AddWithValue("CatId",#Cat1ID);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlSCat1.DataSource = ds;
ddlSCat1.DataTextField = "SubCategory";
ddlSCat1.DataValueField = "SubId";
ddlSCat1.DataBind();
}
ddlSCat1.Items.Insert(0, new ListItem("---Select---", "0"));
}
Howvever,this throws an error.I have tested the stored procedure by using:
Execute spCategory1 '1'
and it works fine.I have tried everything but nothing seems to be working.Help.
The issue lies here :
cmd.Parameters.AddWithValue("CatId",#Cat1ID);
First of all the way you send parameter is wrong. It should be :
cmd.Parameters.AddWithValue("#CatId",Cat1ID);
Second thing the parameter name in your store procedure is #Cat1ID int but you are sending #CatId
remember the parameter name should be same as that of the store procedure, something like this :
cmd.Parameters.AddWithValue("#Cat1ID",Cat1ID);
Correct your code and let me know if that works.

Getting results from a stored procedure to populate a GridView

I have a windows aspx form that I have a TextBox, Button and a GridView. The TextBox is stored as a variable #subschedule and passed to a stored procedure. What I'd like to do is to populate the results of that procedure into my GridView. Can anyone suggest a way to do this?
Thank you
Two popular options:
1.. Code Behind:
string subSchedule = txtSubSchedule.Text.Trim();
//you'll create a new class with a method to get a list of customers
//from your database as others answers have demonstrated
IEnumerable<Customer> custs = MyDataLayer.GetCustomers(subSchedule);
myGrid.DataSource = custs;
myGrid.DataBind();
2.. Use a SqlDataSource. This is a quick and dirty way to bind your ASP.NET server control to a stored procedure. It's got its easy implementation pros, and some other cons :
<asp:GridView id="myGrid"
runat="server"
AutoGenerateColumns="true"
DataSourceID="ds1" />
<asp:SqlDataSource
id="ds1"
runat="server"
ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
SelectCommandType="StoredProcedure"
SelectCommand="GetSchedule">
<SelectParameters>
<asp:ControlParameter name="SubSchedule"
ControlID="txtSubSchedule" Propertyname="Text"/>
</SelectParameters>
</asp:SqlDataSource>
Add a reference to System.Data.SqlClient
Then create a method for your calling your stored procedure... Maybe wrap it up in a class for database calls.
public static class DataBase
{
public static DataTable myProcedureName(String subSchedule)
{
var dt = new DataTable();
using (var cnx = new SqlConnection("myConnectionString"))
using (var cmd = new SqlCommand {
Connection = cnx,
CommandText = "myProcedureName",
CommandType = CommandType.StoredProcedure,
Parameters = {
new SqlParameter("#subSchedule", subSchedule)
}
})
{
try
{
cnx.Open();
dt.Load(cmd.ExecuteReader());
return dt;
}
catch (Exception ex)
{
throw new Exception("Error executing MyProcedureName.", ex);
}
}
}
}
Then call it...
gvMyGrid.DataSource = DataBase.myProcedureName(txtSubSchedule.Text);
gvMyGrid.DataBind();
You'll need to use the DataSource property:
DataTable dt = new DataTable();
// Open the connection
using (SqlConnection cnn = new SqlConnection(
"Data Source=.\sqlexpress;Initial Catalog=AcmeRentals;Integrated Security=True"))
{
cnn.Open();
// Define the command
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = storedProcedureName;
// Define the data adapter and fill the dataset
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
// This is the key code; you can set the DataSource to "collection"
gridView.DataSource = dt.DefaultView;
gridView.DataBind();
Source: http://msmvps.com/blogs/deborahk/archive/2009/07/07/dal-retrieve-a-datatable-using-a-stored-procedure.aspx
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "SPPUBLISHER";
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
connection.Close();
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
Full Source..gridview from procedure

I want to display the mysql table's contents into gridview

what can I do when my all database table's name into dropdown list & when i select or click the table name from dropdown list display the whole field into the gridview dynamically..please give me best solution in asp.net.
Use the mysql commands SHOW TABLES and DESCRIBE table_name and draw the result into grids. I don't know the ASP codes.
(This is an example for MSSQL db. For mysql you can try using OdbcConnection or OleDbConnection depending on MySql version.)
1.Here is direct way to select data:
public class DAL
{
public static DataTable GetTableData(string tableName)
{
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(Settings.Default.ConnectionString))
{
cn.Open();
SqlCommand cmd = cn.CreateCommand();
cmd.CommandText = string.Format("select * from {0}", tableName);
using (SqlDataReader rd = cmd.ExecuteReader())
{
bool ColumnsAdded = false;
while (rd.Read())
{
if (!ColumnsAdded)
{
for (int i = 0; i < rd.FieldCount; i++)
dt.Columns.Add(rd.GetName(i), rd.GetFieldType(i));
}
DataRow row = dt.NewRow();
for (int i = 0; i < rd.FieldCount; i++)
row[i] = rd[i];
dt.Rows.Add(row);
ColumnsAdded = true;
}
}
}
return dt;
}
}
2.Next you drop ObjectDataSource onto your form with a GridView (setting its DataSourceID to objectdatasource). Specify this method on your ObjectDataSource select method. You can specify parameter for tableName to be read from Control (DropDownList1 for instance). DropDownList1 presumebly keeps a list of tables.
You can dynamically load the table contents into gridview by putting a select query for the table and then bind that dataset to gridview datasource.
Hope this helps you!!

fill dropdown list by querystring

I Had Drop down list and I want to fill it with data from database through stored procedure
and it had it,s value when specific query string I had two query string.
as
private void LoadWithCategory()
{
if (Request.QueryString["Category_Id"] != null)
{
using (SqlConnection Con = Connection.GetConnection())
{
SqlCommand Com = new SqlCommand("GetProducFamilyTP", Con);
Com.CommandType = CommandType.StoredProcedure;
Com.Parameters.Add(Parameter.NewInt("#Category_Id", Request.QueryString["Category_Id"]));
SqlDataReader DR = Com.ExecuteReader();
if (DR.Read())
{
DDLProductFamily.DataSource = DR;
DDLProductFamily.DataTextField = DR["Name"].ToString();
DDLProductFamily.DataValueField = DR["ProductCategory_Id"].ToString();
DDLProductFamily.DataBind();
}
DR.Close();
}
}
}
ALTER Proc GetProducFamilyTP
(
#Category_Id Int
)
AS
Select Distinct Categories.Category_Id ,ProductCategory.Name ,
ProductCategory.ProductCategory_Id
From Category_ProductCategory
Inner Join Categories
On
Category_ProductCategory.Category_Id=Categories.Category_Id
Inner Join ProductCategory
On
Category_ProductCategory.ProductCategory_Id=ProductCategory.ProductCategory_Id
Where
Categories.Category_Id =#Category_Id
but this error occurred
DataBinding: 'System.Data.Common.DataRecordInternal' does not contain a property with the name '4Door'.
The error was in ddl list when I removed it it worked well it had value=0

Asp.Net select in Sql

This is going to be very simple I know. I have seen so many different ways of using sql in asp.net with no real standard. What I want to know is how to cleanly select from an sql database in asp.net and retrieve multiple records. For example: select all userids.
String sql =
"SELECT [UserId] FROM [UserProfiles] WHERE NOT [UserId] = 'CurrentUserId'";
string strCon = System.Web
.Configuration
.WebConfigurationManager
.ConnectionStrings["SocialSiteConnectionString"]
.ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
/*
This is where I need to know how to retrieve the information from the
above command(comm). I am looking for something similiar to php's
mysql_result. I want to access the records kind of like an array or some
other form of retrieving all the data.
Also when the new SqlCommand is called...does that actual run the
SELECT STATEMENT or is there another step.
*/
conn.Close();
I think that this is what you are looking for.
String sql = "SELECT [UserId] FROM [UserProfiles] WHERE NOT [UserId] = 'CurrentUserId'";
string strCon = System.Web
.Configuration
.WebConfigurationManager
.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader nwReader = comm.ExecuteReader();
while (nwReader.Read())
{
int UserID = (int)nwReader["UserID"];
// Do something with UserID here...
}
nwReader.Close();
conn.Close();
I do have to say, though, that the overall approach can use a lot of tuning. First, you could at least start by simplifying access to your ConnectionString. For example, you could add the following to your Global.asax.cs file:
using System;
using System.Configuration;
public partial class Global : HttpApplication
{
public static string ConnectionString;
void Application_Start(object sender, EventArgs e)
{
ConnectionString = ConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
}
...
}
Now, throughout your code, just access it using:
SqlConnection conn = new SqlConnection(Global.ConnectionString);
Better yet, create a class in which the "plumbing" is hidden. To run the same query in my code, I'd just enter:
using (BSDIQuery qry = new BSDIQuery())
{
SqlDataReader nwReader = qry.Command("SELECT...").ReturnReader();
// If I needed to add a parameter I'd add it above as well: .ParamVal("CurrentUser")
while (nwReader.Read())
{
int UserID = (int)nwReader["UserID"];
// Do something with UserID here...
}
nwReader.Close();
}
This is just an example using my DAL. However, notice that there is no connection string, no command or connection objects being created or managed, just a "BSDIQuery" (which does lots of different things in addition to that shown). Your approach would differ depending on the tasks that you do most often.
Most of the time, I use this (note that I am also using a connection pooling approach):
public DataTable ExecuteQueryTable(string query)
{
return ExecuteQueryTable(query, null);
}
public DataTable ExecuteQueryTable(string query, Dictionary<string, object> parameters)
{
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = query;
if (parameters != null)
{
foreach (string parameter in parameters.Keys)
{
cmd.Parameters.AddWithValue(parameter, parameters[parameter]);
}
}
DataTable tbl = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(tbl);
}
return tbl;
}
}
}
Here's an adaption of your existing code:
String sql = "SELECT [UserId] FROM [UserProfiles] WHERE [UserId] != #CurrentUserId";
string strCon = System.Web
.Configuration
.WebConfigurationManager
.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
DataTable result = new DataTable();
using (var conn = new SqlConnection(strCon))
using (var cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#CurrentUserID", SqlDbType.Int).Value = CurrentUserID;
conn.Open();
result.Load(cmd.ExecuteReader());
}
Creating a SqlCommand doesn't execute it at all.
The command will be executed when you call ExecuteReader or something similar.
If you want something which will fetch all the results into memory, you should be looking at DataSet/DataTable. There's a tutorial for them here - or there are plenty of others on the net, and any decent ADO.NET book will cover them too.
If you don't want to fetch them all into memory at once, then ExecuteReader it the method for you. That will return a SqlDataReader which is like a database cursor - it reads a row at a time, and you ask for individual columns as you want them, calling Read to get to the next row each time.
Whereas in PHP you'd do something like,
while ($row = mysql_fetch_array ($result))
{
//this assumes you're doing something with foo in loop
$foo = $row["userid"];
//using $foo somehow
}
in .NET, you do something different. Believe me, originating from a PHP background, the transition from PHP to .NET is not easy. There's a lot of things that will seem bizarre. After a while though, it will make sense! Just stick it out. I personally like it better.
Ok.. assuming you have a DataSet like you say, you can do something like this,
//assuming you have a DataSet called myDataSet
for (int i = 0; i < myDataSet.Tables[0].Rows.Count; i++)
{
//likewise assuming here you're doing something with foo in loop
string foo = myDataSet.Tables[0].Rows[i]["userid"].ToString();
//similarly do something with foo in loop
}
That does the same thing as the PHP snippet.

Resources