Binding Checklistbox with SqlServerDatabase - asp.net

I want to Bind a checklistbox with Database in sqlserver2008. I am working in asp.net C# on a user control Module. I wrote a code. i want to know whether the code is perfact or not and also want to know that in which event i should place this code to get proper output.
{
int Post_Id = int.Parse(ViewState["ID"].ToString());
SqlConnection cn1 = new SqlConnection();
cn1.ConnectionString=
ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("SelectTags", cn1);
DataTable ds = new DataTable();
SqlCommand cmnd1 = new SqlCommand("SelectTags", cn1);
cmnd1.Parameters.AddWithValue("#Post_Id",Post_Id);
cmnd1.CommandType = CommandType.StoredProcedure;
cn1.Open();
cmnd1.ExecuteNonQuery();
da.Fill(ds);
cn1.Close();
foreach (DataRow dr in ds.Rows)
{
String field1 = dr["Tag_Name"].ToString();
CheckBoxList2.Items.Add(field1);
CheckBoxList2.DataBind();
}
}
SQL query for sql server 2008
GO
/****** Object: StoredProcedure [dbo].[InsertPost2Tag] Script Date: 04/02/2013 09:47:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Alter PROCEDURE [dbo].[SelectTags]
-- Add the parameters for the stored procedure here
#Post_Id int
AS
BEGIN
SELECT mst_Tag.Tag_Name FROM mst_Tag INNER JOIN Post2Tag ON mst_Tag.tagId = Post2Tag.Tag_Id Where Post2Tag.Post_Id=#Post_Id
END
GO

Do this in page load witin
if(!ispostback){
CheckBoxList2.DataSource = ds; //This is the dataset that you fill from your stored procedure;
CheckBoxList2.DataTextField = "Tag_Name";
CheckBoxList2.DataValueField = "Tag_Name_Id";
CheckBoxList2.DataBind();
}
and take one more parameter Tag_Name_Id in your sp query..
SELECT mst_Tag.Tag_Name,Tag_Name_Id FROM mst_Tag INNER JOIN Post2Tag ON mst_Tag.tagId = Post2Tag.Tag_Id Where Post2Tag.Post_Id=#Post_Id
Remove this from your code
foreach (DataRow dr in ds.Rows)
{
String field1 = dr["Tag_Name"].ToString();
CheckBoxList2.Items.Add(field1);
CheckBoxList2.DataBind();
}
Hope this helps... If it is what you were asking for?

No need to do any thing Just choose data source for check list box and set the session variable with selected value of grid view in its selected index changed event.
It worked for me... and too easy to implement.

Related

Sending multiple parameters from Asp.Net to my stored procedure in SQL Server

I have a list box in Asp.Net from where the user selects one or multiple parameters and send it to a stored procedure. The selected of number of parameters depends completely on the user so I don't know how many parameters the user is going to choose from the list box. I also want to retrieve data back from the table with those parameters when I click on the Submit button and display on a gridview. The issue I am having is I can send one parameter and retrieve data back from my stored procedure but I really don't know how to send multiple parameters from the list box to my stored procedure.
Below is the code for single parameter in Asp.Net
protected void Button_Click(object sender, EventArgs e)
{
string s = "Submit";
SqlCommand cmd = new SqlCommand(s, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = lbCT.SelectedItem.Value;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvDS.DataSource = ds;
gvDS.DataBind();
con.Close();
}
Below is my stored procedure in SQL Server
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [Submit]
#Name VARCHAR(12)
AS
BEGIN
SELECT *
FROM Employee
WHERE Name = #Name
END
You are sending just parameter and using equals "=" operator. Instead of this, you should send all selected items and split your parameter by delimiter.
Please follow these steps:
1.Create a new sql function for split name/names
CREATE FUNCTION dbo.splitstring (#stringToSplit VARCHAR(MAX))
RETURNS
#returnList TABLE ([Name] [nvarchar] (500))
AS
BEGIN
DECLARE #name NVARCHAR(255)
DECLARE #pos INT
WHILE CHARINDEX(',', #stringToSplit) > 0
BEGIN
SELECT #pos = CHARINDEX(',', #stringToSplit)
SELECT #name = SUBSTRING(#stringToSplit, 1, #pos-1)
INSERT INTO #returnList
SELECT #name
SELECT #stringToSplit = SUBSTRING(#stringToSplit, #pos+1, LEN(#stringToSplit)-#pos)
END
INSERT INTO #returnList
SELECT #stringToSplit
RETURN
END
2.Update your procedure
WHERE Name in (Select dbo.splitstring (#Names))
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [Submit]
#Names VARCHAR(MAX)
AS
BEGIN
SELECT *
FROM Employee
WHERE Name in (Select dbo.splitstring (#Names))
END
3.Update your Codebehind parameter
cmd.Parameters.Add("#Names", SqlDbType.VarChar).Value = join all
selected items with ','
protected void Button_Click(object sender, EventArgs e)
{
string s = "Submit";
SqlCommand cmd = new SqlCommand(s, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Names", SqlDbType.VarChar).Value = /*join all selected items with ','*/
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvDS.DataSource = ds;
gvDS.DataBind();
con.Close();
}

Inserting into sql database using the function

I am new in programming, especially in using sql server . I have a User page with text boxes and submit button. When a user enters information to text boxes and press the button, the information is added to database. There is a column UserID in the database which should be created after all information is added to the database.UserID should be consist of UserLastName and AutoIncrementNumber(column of the database which automatically is assigned to a new row) I have a function for this UserID column and i don't know how to make everything work. Please help me.
Thank you!
Here is code:
using (SqlConnection conn = new SqlConnection(#"Data Source=MyDataBase;Initial Catalog=MyDataBase;Integrated Security=True;"))
SqlCommand CmdSql = new SqlCommand
("INSERT INTO [tbluser] ([UserID],[UserLastName], [UserFirstName], [UserMiddleInitial] SELECT [dbo].[usernamehandle](#UserFirstName),#UserLastName, #UserFirstName, #UserMiddleInitial", conn);
conn.Open();
CmdSql.Parameters.AddWithValue("#UserLastName", txtNewUserLN.Text.ToString());
CmdSql.Parameters.AddWithValue("#UserFirstName", txtNewUserFN.Text.ToString());
CmdSql.Parameters.AddWithValue("#UserMiddleInitial", txtNewUserMI.Text.ToString());
CmdSql.Connection = conn;
CmdSql.ExecuteNonQuery();
conn.Close();
And here is function:
USE [MyDataBase]
GO
/****** Object: UserDefinedFunction [dbo].[usernamehandle] Script Date: 04/07/2013 17:25:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[usernamehandle]
(#newuserName nchar(10))returns nchar(10)
AS
BEGIN
DECLARE #s2 nchar(256)
SET #s2 = ''
DECLARE #p int
DECLARE #ULN char(256)
DECLARE #UNAI int
SELECT #ULN = UserLastName FROM tblUser
SELECT #UNAI = UserNameAutoIncre FROM tbluser
SET #s2 = #UNAI
while #p <=6 begin
DECLARE #c int
SET #c = ascii(substring(#newUserName, #p, 1))
SET #s2 += char(#c)
end
return #s2
end
Try to call directly your function in SQL:
Notes: please check the parameter for the function. I am assuming the parameter is user's first name.
SqlCommand CmdSql = new SqlCommand
("INSERT INTO [tbluser] ([UserID],[UserLastName], [UserFirstName], [UserMiddleInitial]) SELECT [dbo].[usernamehandle](#UserFirstName), #UserLastName, #UserFirstName, #UserMiddleInitial, conn);
You can't use function to insert data, function only used for select statement means only for DDL not for DML, for that you have to use Stored Procedure.

why doesn't the c# update query for storedprocedure work?

This question arises out of a net article to insert and update a row of a GridView in a popup window. here.
Clicking on the edit button in GridView, you get a popup window for edit. You edit the window and click 'save' to save it in database. the save method is :
protected void Save(object sender, EventArgs e)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
//cmd.CommandText = "AddUpdateCustomer";
cmd.CommandText = "UPDATE [Customers] SET [CompanyName] = #CompanyName ,[ContactName] = #ContactName WHERE CustomerID = #CustomerID";
cmd.Parameters.AddWithValue("#CustomerID", txtCustomerID.Text);
cmd.Parameters.AddWithValue("#ContactName", txtContactName.Text);
cmd.Parameters.AddWithValue("#CompanyName", txtCompany.Text);
GridView1.DataSource = this.GetData(cmd);
GridView1.DataBind();
cmd.ExecuteNonQuery();
}
}
The online article used the commented line for cmd.CommandText which I changed as that did not work nor did I find its utility. I also added the last line cmd.ExecuteNonQuery(); to execute the query But actually no change in DB.
What might be wrong with the Save method and how to deal with that wrong ?
You've requested a call to a stored procedure, but the line you commented-out is the one that contains the stored procedure name.
It looks like you're actually executing raw SQL so you should try instead:
cmd.CommandType = CommandType.Text;
But your CommandText line won't work either because it isn't real SQL. It needs to include the content of the variables rather than the variable names. And also you should be executing a query rather than a non-query.
protected void Save(object sender, EventArgs e)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Concat("UPDATE [Customers] SET [CompanyName] = ", txtCompany.Text, ", [ContactName] = ", txtContactName.Text, " WHERE CustomerID = ", txtCustomerId.Text, ";");
etc
You need to write your code for filling Textbox's at page load as below :
public page_load()
{
if(!ispostBack)
{
// Write code to fill controls first time
}
}
this is because on every postback asp.net will save the controls value in viewstate and when page return from server controlls are filled with old value and database table will update with old value rather than new value

oraclehelper filldataset or another way to get SYS_REFCURSOR values at ASP.NET

To whom it may respond to,
We are developing our project using .net framework 4.0,Oracle 11gR2. The problem is that , we have to use Oraclehelper class, no other options, and we can't get SYS_REFCURSOR values . When googled ,
we have catched some pages writing about filldataset method of oraclehelper class, but this class doesn't exist in our Oraclehelper class.
Any workarounds, templates, examples etc. to get SYS_REFCURSOR values via Oraclehelper class?
Thank you for your concern,
Best Regards,
Kayhan YÜKSEL
assuming you are using the sourceforge.net/projects/oraclehelpernet "oraclehelper" it is build ontop of ODP (ie Oracle.DataAccess.Client)
all you would need to do is:
(this is from http://download.oracle.com/docs/cd/B28359_01/win.111/b28375/featRefCursor.htm)
String cmdTxt1 = "begin open :1 for select col1 from test; end;";
OracleCommand cmd = new OracleCommand(cmdTxt1, conn);
OracleParameter outRefPrm = cmd.Parameters.Add("outRefPrm",
OracleDbType.RefCursor, DBNull.Value, ParameterDirection.Output);
cmd.ExecuteNonQuery(); // Execute the anonymous PL/SQL block
You can also look in %oracle_home%\client_1\odp.net\samples\4\RefCursor for 7 examples (this is when ODP is installed that is)
Since the OracleHelper just creates a wrapper around ODP, all you need to do is create the parameter as OracleDbType.RefCursor and pass it into the call (be it an execute non-query or datareader or whatnot)
now to do this via a procedure:
PROCEDURE Get1CurOut(p_cursor1 out refCursor) is
BEGIN
OPEN p_cursor1 for select * from emp;
END Get1CurOut;
and to the C#
OracleCommand cmd = new OracleCommand("Get1CurOut", con);
cmd.CommandType = CommandType.StoredProcedure;
// Bind
OracleParameter oparam = cmd.Parameters.Add("refcursor", OracleDbType.RefCursor);
oparam.Direction = ParameterDirection.Output;
try
{
// Execute command; Have the parameters populated
cmd.ExecuteNonQuery();
// Create the OracleDataAdapter
OracleDataAdapter da = new OracleDataAdapter(cmd);
// Populate a DataSet with refcursor1.
DataSet ds = new DataSet();
da.Fill(ds, "refcursor1", (OracleRefCursor)(cmd.Parameters["refcursor1"].Value));
// Print out the field count the REF Cursor
Console.WriteLine("Field count: " + ds.Tables["refcursor1"].Columns.Count);
}
this is lifted (with slight modification) from %oracle_home%\client_1\odp.net\samples\4\RefCursor\sample1.cs
here is an (untested) OracleHelper example:
string connectionString = "User Id=scott;Password=tiger;Data Source=oracle";
CommandType commandType = CommandType.StoredProcedure;
string commandText = "Get1CurOut";
OracleParameter oparam = cmd.Parameters.Add("refcursor", OracleDbType.RefCursor);
oparam.Direction = ParameterDirection.Output;
OracleDataReader reader;
reader = OracleHelper.ExecuteReader(connectionString, commandType, commandText, oparam) ;
// show the first row
reader.Read();
// Print out SCOTT.EMP EMPNO column
Console.WriteLine("EMPNO: {0}", reader.GetDecimal(0));
// Print out SCOTT.EMP ENAME column
Console.WriteLine("ENAME: {0}", reader.GetString(1));

SQL Cache Dependency not working with Stored Procedure

I can't get SqlCacheDependency to work with a simple stored proc (SQL Server 2008):
create proc dbo.spGetPeteTest
as
set ANSI_NULLS ON
set ANSI_PADDING ON
set ANSI_WARNINGS ON
set CONCAT_NULL_YIELDS_NULL ON
set QUOTED_IDENTIFIER ON
set NUMERIC_ROUNDABORT OFF
set ARITHABORT ON
select Id, Artist, Album
from dbo.PeteTest
And here's my ASP.NET code (3.5 framework):
-- global.asax
protected void Application_Start(object sender, EventArgs e)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString;
System.Data.SqlClient.SqlDependency.Start(connectionString);
}
-- Code-Behind
private DataTable GetAlbums()
{
string connectionString =
System.Configuration.ConfigurationManager.ConnectionStrings["UnigoConnection"].ConnectionString;
DataTable dtAlbums = new DataTable();
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Works using select statement, but NOT SP with same text
//SqlCommand command = new SqlCommand(
// "select Id, Artist, Album from dbo.PeteTest", connection);
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.spGetPeteTest";
System.Web.Caching.SqlCacheDependency new_dependency =
new System.Web.Caching.SqlCacheDependency(command);
SqlDataAdapter DA1 = new SqlDataAdapter();
DA1.SelectCommand = command;
DataSet DS1 = new DataSet();
DA1.Fill(DS1);
dtAlbums = DS1.Tables[0];
Cache.Insert("Albums", dtAlbums, new_dependency);
}
return dtAlbums;
}
Anyone have any luck with getting this to work with SPs?
Thanks!
i figured this out, need to set query options BEFORE creating the SP. got it working when i created the SP as follows:
USE [MyDatabase]
GO
set ANSI_NULLS ON
set ANSI_PADDING ON
set ANSI_WARNINGS ON
set CONCAT_NULL_YIELDS_NULL ON
set QUOTED_IDENTIFIER ON
set NUMERIC_ROUNDABORT OFF
set ARITHABORT ON
go
create proc [dbo].[spGetPeteTest]
as
select Id, Artist, Album
from dbo.PeteTest
GO
You are not returning data from the cache every time. It should be like this:
if (Cache["Albums"]!=null)
{
return (DataTable) Cache["Albums"];
}
else
{
// you need to write coding from database.
}
Another cause can be this in a SQL statement:
AND dbo.[PublishDate] <= GetDate()
The SQLCacheDependency will behave as if the underlying data has changed even if it hasn't, since GetDate() is dynamic (equally if you were to pass DateTime.Now via a #parameter).
This was not obvious to me after re-writing my proc following all the good suggestions above, also not forgetting also to remove "SET NOCOUNT ON" from the proc. SQLCacheDependency expires the cache if the data changes OR the query parameters values change, which makes sense I suppose.
For me using something like this in the stored proc didn't work.
select id, name from dbo.tblTable;
I had to explicitly put in the references like this.
select dbo.tblTable.id, dbo.tblTable.name from dbo.tblTable;
SQL caching won't work if you use select *, also you need to make sure you put dbo (or relevant schema) in front of your table name.
You can also check SQL profiler to verify if your sql is run hope will help you etc....
Note that you cannot use
with (NOLOCK)
in the stored procedure or the the dependency will remain constantly invalid.
This does not appear to be mentioned in the documentation as far as I can tell
I realise that the original poster did not do this but anyone coming here that has the problem stated in the title may have done this so I thought it was worth mentioning.

Resources