how to write select parameterized query in asp.net - asp.net

Below code is written to call parameterized select query in asp.net
public bool checkConflictTime()
{
bool TimeExists = false;
DataSet ds = new DataSet();
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
string sql = #"SELECT * FROM Images WHERE starttime= #starttime AND endtime = #endtime";
SqlCommand sqlcommand = new SqlCommand(sql,sqlconn);
//sqlcommand.Connection = sqlconn;
//string sql = "CheckConflictTimings";
sqlcommand.CommandType = CommandType.Text;
sqlcommand.CommandText = sql;
sqlcommand.Parameters.Add(new SqlParameter("#starttime", ddlStartTime.SelectedItem.Text));
sqlcommand.Parameters.Add(new SqlParameter("#endtime", ddlEndTime.SelectedItem.Text));
SqlDataAdapter da = new SqlDataAdapter(sql, sqlconn);
try
{
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
TimeExists = true;
}
}
catch (Exception ex)
{
}
finally
{
sqlconn.Close();
sqlconn.Dispose();
}
return TimeExists;
}
Is there something wrong? it threw error of :Must declare the scalar variable "#starttime"
when filling data adapter.

Try
SqlDataAdapter da = new SqlDataAdapter(sqlcommand);

Try
sqlcommand.Parameters.Add(new SqlParameter("starttime", ddlStartTime.SelectedItem.Text));
I don't think you need the # prefix when adding the parameter.

I think you're not passing your command as a SelectCommand to the adapter.
da.SelectCommand = sqlcommand;

Try
sqlcommand.Parameters.AddWithValue("#starttime",ddlStartTime.SelectedItem.Text);
instead of
sqlcommand.Parameters.Add(new SqlParameter("#starttime", ddlStartTime.SelectedItem.Text));

Related

Connecting MS_SQL DB IN asp.net

I was trying to connectMs_sql database in asp.net but server error of network path not found... it is not able to establish connection to sql server...comes while in gridview it is taking it as sqldatasource perfectly
This for customized class to call the ADO.Net. Please use this and let me know if you have any doubts.
public class DbConnectionHelper {
public DataSet DBConnection(string TableName, SqlParameter[] p, string Query, CommandType cmdText) {
string connString = # "your connection string here";
//Object Declaration
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
try {
//Get Connection string and Make Connection
con.ConnectionString = connString; //Get the Connection String
if (con.State == ConnectionState.Closed) {
con.Open(); //Connection Open
}
if (cmdText == CommandType.StoredProcedure) //Type : Stored Procedure
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = Query;
if (p.Length > 0) // If Any parameter is there means, we need to add.
{
for (int i = 0; i < p.Length; i++) {
cmd.Parameters.Add(p[i]);
}
}
}
if (cmdText == CommandType.Text) // Type : Text
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
}
if (cmdText == CommandType.TableDirect) //Type: Table Direct
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
}
cmd.Connection = con; //Get Connection in Command
sda.SelectCommand = cmd; // Select Command From Command to SqlDataAdaptor
sda.Fill(ds, TableName); // Execute Query and Get Result into DataSet
con.Close(); //Connection Close
} catch (Exception ex) {
throw ex; //Here you need to handle Exception
}
return ds;
}
}

data source does not support server-side data paging

i am currently trying to do paging for my gridview but once i allow paging in my gridview it will give me this error : The data source does not support server-side data paging.
this is my code for gridview :
SqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataSourceID = null;
GridView1.Visible = true;
GridView1.AllowPaging= true;
GridView1.DataBind();
conn.Close();
SqlDataReader is forward-only. Server-side Paging needs to be able to traverse the datasource both backward and forward. Use a different datasource, like SqlDataAdapter, which supports bi-directional traversal.
Example (as requested):
string query = string.Empty;
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataAdapter da = null;
DataSet ds = null;
try {
query = "SELECT * FROM table WHERE field = #value";
conn = new SqlConnection("your connection string");
cmd = new SqlCommand(query, conn);
cmd.Parameters.Add("value", SqlDbType.VarChar, 50).Value = "some value";
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables.Count > 0) {
GridView1.DataSource = ds.Tables(0);
GridView1.AllowPaging = true;
GridView1.DataBind();
}
} catch (SqlException ex) {
//handle exception
} catch (Exception ex) {
//handle exception
} finally {
if (da != null) {
da.Dispose();
}
if (cmd != null) {
cmd.Dispose();
}
if (conn != null) {
conn.Dispose();
}
}
SqlDataAdapter is also from the System.Data.SqlClient Namespace.
Have you tried using a SqlDataAdapter to fill a DataSet/DataTable with your SQL results? Then use that DataTable as your data source for the GridView. Basic framework for filling your DataTable:
public DataTable GetDataTable(String connectionString, String query)
{
DataTable dataTable = new DataTable();
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{
dataAdapter.Fill(dataTable);
}
}
}
}
catch
{
}
return dataTable;
}
And then you can use that DataTable as your GridView DataSource:
String connectionString = "Data Source=<datasource>;Initial Catalog=<catalog>;User Id=<userID>;Password=<password>;";
String query = "SELECT * FROM TABLE_NAME WHERE ID=BLAH";
GridView1.DataSource = GetDataTable(connectionString, query);
GridView1.DataSourceID = null;
GridView1.Visible = true;
GridView1.AllowPaging= true;
GridView1.DataBind();
Hopefully this will help.
You can apply paging to a gridview in two ways
(1) Use an object datasource with your gridview
(2) Use jquery Datatable

Detailsview in ASP.NET

I am trying to hit sql server with objectdatasource and return a datatable to fill my details view control. the selected ID value is returned by a gridview control. It seems like the datatable is not filled by adapter, and i couldn't figure out why. The ID in sql is set as a primary key (Int, 4, not null). The debugger says the Detail datatable is null. Any help is much appreciated.
public DataTable GetDetail(string ID)
{
if (ID == "")
{
return null;
}
else
{
DataTable Detail = null;
using (SqlConnection conn = new SqlConnection(connection))
{
string comm = #"select * from dbo.Products where ID = #ID";
conn.Open();
SqlDataAdapter adapter=null;
using (SqlCommand cmd = new SqlCommand(comm, conn))
{
cmd.Parameters.Add("ID", System.Data.SqlDbType.Int, 4).Value = Convert.ToInt32(ID);
adapter = new SqlDataAdapter(cmd);
adapter.Fill(Detail);
return Detail;
}
}
}
I think you missed the commandType
cmd.CommandType = CommandType.Text;
Try this
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(connection))
{
string myquery="select * from dbo.Products where ID = #ID";
SqlCommand cmd = new SqlCommand(myquery, con);
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = cmd;
cmd.Parameters.Add("#ID", SqlDbType.NVarChar, 15).Value = ID;
dap.Fill(ds);
return ds.Tables[0];
}
Thanks for ALL.
The problem is I didnt initialize my datatable to a new instance.
DataTable Detail = null; ===> DataTable Detail = new Datatable();
and also the convert should be done in sql not in codes.
cmd.Parameters.Add("ID", System.Data.SqlDbType.Int, 4).Value = ID;
string comm = #"select * from dbo.Products where ID = convert(int,#ID)";

sql stored procedure in asp.net not running

A little background on what I'm doing.
I have a button that has a click call which takes me to this code.
static public DataSet shareFiles(TransitoryRegObj argTransRegObj)
{
string sqlString = "do_share_files"; // it's a stored procedure
SqlConnection cnn = new SqlConnection(masterConn);
SqlCommand comm = new SqlCommand(sqlString, cnn);
DataSet ds = new DataSet();
try
{
cnn.Open();
SqlCommand Comm = new SqlCommand(sqlString, cnn);
Comm.CommandType = CommandType.StoredProcedure;
comm.Dispose();
cnn.Close();
return ds;
}
catch (Exception ex)
{
// log here should anything go wrong with anything
// lblmessage.Text = "Error: " + ex.Message;
if (comm != null)
comm.Dispose();
if (cnn != null)
cnn.Close();
DataTable dt = new DataTable("ExceptionTable");
dt.Columns.Add("ExceptionMessage");
dt.Rows.Add(ex.Message);
ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}
}
The code runs fine however nothing is written to database. here is do_share_files stored procedure.
ALTER PROCEDURE [dbo].[do_share_files]
--#device_id bigint, #user_id bigint, #file_name varchar(50),#full_up_path varchar(50), #upLength varchar(30)
--,#mime_type varchar(20), #filedate varchar(30)
AS
BEGIN
insert into [user_files] (device_id, user_id, original_name, original_path, up_path, content_type, up_dt)
values (17, 30, 'test.pg', 'test.pg', 'test.pg','test.pg', '2012-11-15 03:58:06.043')
END
I have static values for now since i'm just trying to get it to run to stored procedure.
I'm new to asp.net and don't know what i'm doing wrong. Any help would be appreciated.
Thanks!
You could start with this:
static public DataSet shareFiles(TransitoryRegObj argTransRegObj)
{
string sqlString = "do_share_files"; // it's a stored procedure
DataSet ds = new DataSet();
try
{
using (var cnn = new SqlConnection(masterConn))
{
SqlCommand comm = new SqlCommand(sqlString, cnn);
comm.CommandType = CommandType.StoredProcedure;
cnn.Open();
comm.ExecuteNonQuery ();
To summarize:
Comm and comm are different commands;
To run the proc, you need to call ExecuteNonQuery or other Execute method.
Your code has few mistakes
1. I cant understand why you are using this line twice
SqlCommand comm = new SqlCommand(sqlString, cnn);
2. You didnot execute the procedure which is the main problem
static public DataSet shareFiles(TransitoryRegObj argTransRegObj)
{
try
{
string sqlString = "do_share_files"; // it's a stored procedure
SqlConnection cnn = new SqlConnection(masterConn);
SqlCommand comm = new SqlCommand(sqlString, cnn);
DataSet ds = new DataSet();
cnn.Open();
Comm.CommandType = CommandType.StoredProcedure;
comm.ExecuteNonQuery();
comm.Dispose();
cnn.Close();
return ds;
}
catch (Exception ex)
{
//something here
}
}

how to from select parameterized query in asp.net

I want to write parametrized query for select statement. but it gives exception that "Must declare the variable '#'." how to declare this variable .
My code is given below:
SqlConnection con = null;
SqlCommand cmd = null;
try
{
//int #[MONTH_FOR], #[YEAR_FOR];
con = new SqlConnection("Data Source=192.168.10.3;Initial Catalog=GPSTrainees;user id=gp;password=gp");
con.Open();
string select = #"SELECT [COMPONENT_NAME] ,[COMPONENT_AMOUNT]
FROM [GoalPlanForTrainees].[gp].[TEAM_FUNDS_DETAILS]
WHERE [MONTH_FOR] = #[MONTH_FOR] AND [YEAR_FOR] = #[YEAR_FOR]";
cmd = new SqlCommand(select, con);
cmd.Parameters.Add(new SqlParameter("#[MONTH_FOR]", Convert.ToInt32( TextBox1.Text.Trim())));
cmd.Parameters.Add(new SqlParameter("#[YEAR_FOR]",Convert.ToInt32(TextBox2.Text.Trim())));
DataSet ds = new DataSet();
SqlDataAdapter adp = new SqlDataAdapter(select, con);
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception ex)
{
}
finally
{
if (con != null)
{
con.Close();
}
}`enter code here`
While creating the parameters, please remove the "#" in front of the Parameter name. Something like this:
cmd.Parameters.Add(new SqlParameter("[MONTH_FOR]", Convert.ToInt32(TextBox1.Text.Trim())));
Hopefully this should help.
Put the variable declaration in the sql statement. So move int #[MONTH_FOR], #[YEAR_FOR];
to
#"int #[MONTH_FOR], #[YEAR_FOR]; SELECT [COMPONENT_NAME] ,[COMPONENT_AMOUNT] FROM [GoalPlanForTrainees].[gp].[TEAM_FUNDS_DETAILS] WHERE [MONTH_FOR] = #[MONTH_FOR] AND [YEAR_FOR] = #[YEAR_FOR]";
Cheers Tigger
try this
int MONTH_FOR=#monthFor
command.Parameters.Add(MONTH_FOR, SqlDbType.int).Value = value

Resources