Only show values of combobox like "love"? - c#

I created a store procedure to select all values of the table.
But I want in C# application, combobox only show values start like love keyword.
Example:
love love
love king
love soft
Don't show item:
long time
union all
My code:
public void HienThiLoaiBCao()
{
LovetoDAL cal = new LovetoDAL();
string keyword = "BC";
int i = cbxTenBaoCao.FindString(keyword);
if (i == -1)
return;
else
{
var dt = cal.Love_GetByTop("", "", "ID DESC");
cbxTenBaoCao.DataSource = dt;
cbxTenBaoCao.DisplayMember = "lover";
cbxTenBaoCao.ValueMember = "lover";
}
}
public DataTable Love_GetByTop(string Top, string Where, string Order)
{
using (var cmd = new SqlCommand("sq_Love_GetByTop", GetConnection()))
{
cmd.CommandType = CommandType.StoredProcedure;
var da = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#Top", Top));
cmd.Parameters.Add(new SqlParameter("#Where", Where));
cmd.Parameters.Add(new SqlParameter("#Order", Order));
var dt = new DataTable();
da.Fill(dt);
return dt;
}
}
USE [LEO]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sq_Love_GetByTop]
#Top nvarchar(10),
#Where nvarchar(500),
#Order nvarchar(500)
AS
Declare #SQL as nvarchar(500)
Select #SQL = 'SELECT top (' + #Top + ') * FROM [Love]'
if len(#Top) = 0
BEGIN
Select #SQL = 'SELECT * FROM [Love]'
END
if len(#Where) >0
BEGIN
Select #SQL = #SQL + ' Where ' + #Where
END
if len(#Order) >0
BEGIN
Select #SQL = #SQL + ' Order by ' + #Order
END
EXEC (#SQL)
Thanks.

One option is to filter out the records that starts with love from your DataTable. You can either use Select method on DataTable directly OR use RowFilter property on default DataView of the table and then bind the filtered results to your combo box.
Something like this with DataView -
DataView dv = dt.DefaultView;
//Apply your filter on data view, for records starting with `love`
dv.RowFilter = "lover like 'love*'";
//and bind you combo box with the data view
cbxTenBaoCao.DataSource = dv;
Rest of the code would be as is.
More on filtering result sets -
http://www.csharp-examples.net/dataview-rowfilter/
https://msdn.microsoft.com/en-us/library/system.data.datatable.select%28v=vs.110%29.aspx

i did not try this code, it's a long time since i code c#.
//get the values from your stored procedure
List<string> values = task.storedProcedures();
//remove items that doesn't start with "love"
values = values.Where(item => item.someValues.StartsWith("love"))
Hope this helps

Related

Index out of range on column from inner join condition

I am getting a index out of range error when trying to get a string value from a datareader. The column USER_ROLE which is the only column from a INNER JOIN condition. It was working and for some reason has now started throwing this index out of range error. I've verified the actual stored procedure works via SSMS and the column is being returned.
Below is the code for the stored procedure
ALTER PROCEDURE [dbo].[usp_GetUsersLogonInformation]
(
-- inactive = 0, active = 1, all = 2
#active int = 2
)
AS
BEGIN
DECLARE #whereClauseNeeded bit = 1
DECLARE #whereClause nvarchar(100) = concat(' WHERE usr.ACTIVE = ', #active)
DECLARE #sqlCmd nvarchar(max)= 'SELECT
usr.USER_PK,
usr.PRINCIPAL_ID,
usr.AA_USER_FK,
usr.FIRST_NAME,
usr.LAST_NAME,
usr.[USER_NAME],
usr.EMAIL_ADDRESS,
usr.ACTIVE,
usr.LV_USER_ROLE_FK,
lvur.USER_ROLE,
usr.CREATED_BY,
usr.CREATED_SYSDATE
FROM dbo.USERS usr
INNER JOIN dbo.LV_USER_ROLES lvur ON lvur.LV_USER_ROLE_PK = usr.LV_USER_ROLE_FK'
IF #active = 0 OR #active = 1
BEGIN
set #sqlCmd = concat(#sqlCmd, #whereClause)
END
EXEC sp_executesql #sqlCmd
END
the c# code retrieving the data
using (SqlConnection dbConn = theVoiceSqlHelpers.GetDbConnection())
{
using (SqlCommand sqlCmd = new SqlCommand(USP_GET_USER_INFO, dbConn))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#whereClause",string.Format("USER_NAME = \'{0}\'", txbxUserName.Text));
SqlDataReader dr = sqlCmd.ExecuteReader();
while (dr.Read())
{
user = new Tbl_Users();
user.USER_PK = dr.GetInt32(dr.GetOrdinal("USER_PK"));
user.PRINCIPAL_ID = dr.GetInt32(dr.GetOrdinal("PRINCIPAL_ID"));
user.AA_USER_FK = dr.GetInt32(dr.GetOrdinal("AA_USER_FK"));
user.FIRST_NAME = dr.GetString(dr.GetOrdinal("FIRST_NAME"));
user.LAST_NAME = dr.GetString(dr.GetOrdinal("LAST_NAME"));
user.USER_NAME = dr.GetString(dr.GetOrdinal("USER_NAME"));
user.EMAIL_ADDRESS = dr.GetString(dr.GetOrdinal("EMAIL_ADDRESS"));
user.ACTIVE = dr.GetBoolean(dr.GetOrdinal("ACTIVE"));
user.LV_USER_ROLE_FK = dr.GetInt32(dr.GetOrdinal("LV_USER_ROLE_FK"));
user.USER_ROLE = dr.GetString(dr.GetOrdinal("USER_ROLE"));
user.CREATED_BY = dr.GetString(dr.GetOrdinal("CREATED_BY"));
user.CREATED_SYSDATE = dr.GetDateTime(dr.GetOrdinal("CREATED_SYSDATE"));
}
dr.Close();
}
}
I have ensure the column name is correct however I am now stuck at this new found exception.
Has anyone seen this behavior before. My apologies if I am overlooking and obvious but could use an extra set of eyes on this.
LV_USER_ROLES Table
USERS Table
Charlieface's comment resolved the exception. In this database there is 2 similiar named usp's and I was calling the wrong one.

Building a dynamic where clause in a stored procedure command

I have a stored procedure where the arguments looks like this
Create Procedure [dbo].[myStoredProcedure]
#TaskId int = 0
, #FileName varchar(200) =''
, #DataDtFrom smalldatetime = '01/01/1900'
, #DataDtTo smalldatetime = '01/01/1900'
, #OFFSET INT = 0
, #FETCH INT = 2000
, #WhereClauseString varchar(5000) = ''
SELECT
DataDt
,EffDt
,LoanNumber
,UploadDate
,UploadedFileName
FROM dbo.myFileTable u
WHERE
(#DataDtTo = '01/01/1900' or DataDt between #DataDtFrom and #DataDtTo)
and (#TaskId = 0 or TaskId = #TaskId)
and (#FileName = '' or UploadedFileName like '%' + #FileName + '%')
**Where ??? = #WhereClauseString**
ORDER BY u.UploadDate
OFFSET #OFFSET ROWS
FETCH NEXT #FETCH ROWS ONLY
I initialize this in C#
var whereClauseString = "LoanNum in(111,222,444) and TaskId in (123,456,789)";
using (var conn = new MyEntities().Database.Connection)
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandTimeout = 1800;
cmd.CommandText = model.UploadStoredProcedure;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#TaskId", Convert.ToInt64(model.TaskId)));
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#FileName", model.FileName ?? string.Empty));
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#DataDtFrom", DateTime.Parse(model.adjFromDataDt.ToShortDateString()) <= DateTime.Parse(basicDate.ToShortDateString()) ? basicDate : model.adjFromDataDt.Date));
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#DataDtTo", DateTime.Parse(model.adjToDataDt.ToShortDateString()) <= DateTime.Parse(basicDate.ToShortDateString()) ? basicDate : model.adjToDataDt.Date));
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#OFFSET", model.Page));
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#FETCH", model.PageSize));
**Dynamic Where clause** -->> System.Data.SqlClient.SqlParameter("#WhereClause", whereClauseString));
var da = new System.Data.SqlClient.SqlDataAdapter((System.Data.SqlClient.SqlCommand)cmd);
da.Fill(ds);
}
My question is it possible to build a dynamic where clause and pass it to the stored procedure and sort on the columns that are being referenced in the where clause?
How would I know which columns I need in the stored procedure that are being referenced in the where clause?
Would such a thing be possible with this stored Procedure and Entity Framework?
Anyway, if your DB is far from external attacks with SQL Injection you still can think in an easy solution based in Dinamic SQL, very often this way can solve quickly very complex problems otherwise:
CREATE Procedure [dbo].[myStoredProcedure]
#TaskId int = 0
, #FileName varchar(200) =''
, #DataDtFrom smalldatetime = '01/01/1900'
, #DataDtTo smalldatetime = '01/01/1900'
, #OFFSET INT = 0
, #FETCH INT = 2000
, #WhereClauseString varchar(5000) = ''
AS
BEGIN
DECLARE #SQL AS NVARCHAR(MAX);
SELECT #SQL = '
SELECT
DataDt
,EffDt
,LoanNumber
,UploadDate
,UploadedFileName
FROM dbo.myFileTable u
WHERE
('''+CONVERT(CHAR(10), #DataDtTo, 112)+''' = ''01/01/1900'' or DataDt between '''+CONVERT(CHAR(10), #DataDtFrom, 112)+''' and '''+CONVERT(CHAR(10), #DataDtTo, 112)+''')
and ('+CONVERT(CHAR(10), #TaskId)+' = 0 or TaskId = '+CONVERT(CHAR(10), #TaskId)+')
and ('+RTRIM(CONVERT(CHAR(100), #FileName))+' = '''' or UploadedFileName like ''%'+RTRIM(CONVERT(CHAR(100), #FileName))+'%'')
' +CONVERT(CHAR(100), #WhereClauseString)+'
ORDER BY u.UploadDate
OFFSET '+CONVERT(CHAR(10), #OFFSET)+' ROWS
FETCH NEXT '+CONVERT(CHAR(10), #FETCH)+' ROWS ONLY;
'
PRINT #SQL;
EXEC sp_ExecuteSQL #SQL;
END;

Insert Error: Column name or number of supplied values does not match table definition.using storedprocedure

I'm getting following error:
Insert Error: Column name or number of supplied values does not match
table definition.
Total column in excel is = 17
Total field in table = 17 + 3 = 20
among 3 fiedls 1 is (primarykeyid-autogenerate) 2 is (will get from another textbox) and 3 is (defaulvalue 1)
i don't know how to pass text box value and default value to procedure.
Please suggest me a way
Here is my stored procedure code
USE [Demo]
GO
/****** Object: StoredProcedure [dbo].[spx_ImportFromExcel07] Script Date: 03/21/2014 18:25:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spx_ImportFromExcel07]
#SheetName varchar(20),
#FilePath varchar(300),
#HDR varchar(3),
#TableName varchar(50)
AS
BEGIN
DECLARE #SQL nvarchar(1000)
IF OBJECT_ID (#TableName,'U') IS NOT NULL
SET #SQL = 'INSERT INTO ' + #TableName + ' SELECT * FROM OPENDATASOURCE'
ELSE
SET #SQL = 'SELECT * INTO ' + #TableName + ' FROM OPENDATASOURCE'
SET #SQL = #SQL + '(''Microsoft.ACE.OLEDB.12.0'',''Data Source='
SET #SQL = #SQL + #FilePath + ';Extended Properties=''''Excel 12.0;HDR='
SET #SQL = #SQL + #HDR + ''''''')...['
SET #SQL = #SQL + #SheetName + ']'
EXEC sp_executesql #SQL
END
and here is my insertion code:
protected void btnSave_Click(object sender, EventArgs e)
{
string FileName = lblFileName.Text;
string Extension = Path.GetExtension(FileName);
string FolderPath = Server.MapPath(ConfigurationManager.AppSettings["FolderPath"]);
string CommandText = "";
switch (Extension)
{
case ".xls": //Excel 97-03
CommandText = "spx_ImportFromExcel03";
break;
case ".xlsx": //Excel 07
CommandText = "spx_ImportFromExcel07";
break;
}
//insertDB();
String strConnString = ConfigurationManager.ConnectionStrings["CARGONETConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = CommandText;
cmd.Parameters.Add("#SheetName", SqlDbType.VarChar).Value = ddlSheets.SelectedItem.Text;
cmd.Parameters.Add("#FilePath", SqlDbType.VarChar).Value = FolderPath + FileName;
cmd.Parameters.Add("#HDR", SqlDbType.VarChar).Value = rbHDR.SelectedItem.Text;
cmd.Parameters.Add("#TableName", SqlDbType.VarChar).Value = "TB_TransAgentSeaFreightRate";
cmd.Connection = con;
try
{
con.Open();
object count = cmd.ExecuteNonQuery();
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = count.ToString() + " records inserted.";
}
catch (Exception ex)
{
lblMessage.ForeColor = System.Drawing.Color.White;
lblMessage.Text = ex.Message;
}
finally
{
con.Close();
con.Dispose();
Panel1.Visible = true;
//Panel2.Visible = false;
dg_AgentSFR.Visible = true;
}
}
Please Help me..
I dont know how to pass textbox value and defaulvalue to storedprocedure.
Thanks in advance
First, I recommend you get rid of the dynamic SQL in your stored procedure. Dynamic SQL will leave you vulnerable to SQL injection. "lblFileName.Text" is the most likely place that I see in the provided code for the injection to occur, but with the way the stored procedure is written, you are vulnerable with every parameter. You should parse the values to the correct types before you call the stored procedure. The parameters in the stored procedure should be the type of the columns in the table respectively. As for the table selection you are making, ask yourself how often this will change?
If it is not practical to write inserts for each table due to a large number of tables, then you need to check the stored procedure's parameters for SQL injection.
If you need a default value, you can easily put it on the stored procedure. Then you can do a check and skip the parameter in the code behind.
Stored Procedure:
CREATE PROCEDURE spExample
#nExample int = 1
AS
Code Behind:
int value
if(int.TryParse(TextBox1.Text, out value))
{
// add parameter here.
}
http://technet.microsoft.com/en-us/library/ms189330(v=sql.105).aspx
http://en.wikipedia.org/wiki/SQL_injection

How to get SQL String Result from Stored Procedure and save it in C# Windows Application string variable

I have the following Stored Procedure :
ALTER PROCEDURE [dbo].[ProcedureName]
#date NVARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #result nvarchar(500) -- this one should return string.
DECLARE #variable1 NVARCHAR(50)
set #variable1 = (SELECT COUNT(*) FROM dbo.Table1 WHERE column1 not in (select column1 from dbo.Table2))
DECLARE #variable2 NVARCHAR(50)
update dbo.Table1 set columnX = 1 where column1 not in (select column1 from dbo.Table2)
set #variable2 = ##ROWCOUNT
and so on... it continues like 200 rows of script with at least 10-12 variables
after that I want to get result like this
'Hello,' +
'Some Text here' +
#date +': ' +
'Explaining text for variable1- ' + #variable1 +
'Updated rows from variable2 - ' + #variable2 +
'some other select count - ' + #variable3 +
'some other update rowcount - '+ #variable4
......
till now i was able to get this with PRINT Statement, but can't take it to variable in my C# code which goes like this:
public void Execute_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to execute the program?", "Confirm Start", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.No)
{
string connectionString = GetConnectionString(usernamePicker.Text, passwordPicker.Text);
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("dbo.ProcedureName", connection))
{
connection.Open();
cmd.CommandText = "dbo.ProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#date", SqlDbType.VarChar).Value = dateTimePicker1.Text;
SqlParameter result = cmd.Parameters.Add("#result", SqlDbType.VarChar);
result.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteScalar();
var resultout = (string)cmd.Parameters["#result"].Value;
connection.Close();
TextMessage.Text = dateTimePicker1.Text;
}
}
}
}
all i get for result is 0 or NULL or etc.
i tried to return value from SQL with PRINT, RETURN, SET, OUTPUT ....... but nothing seems to work. However fetching variable from C# to SQL seems like child-work. Any ideas?
If you want to return the concatenate string as output then at the end of the procedure just write select #result. Make sure that you have concatenated it before this statement.
This will return you the string which you can use in your c# code as a string.
Change your stored procedure to this:
ALTER PROCEDURE [dbo].[ProcedureName]
#date NVARCHAR(50),
#variable1 NVARCHAR(50) output,
#variable2 NVARCHAR(50) output
AS
BEGIN
SET NOCOUNT ON;
DECLARE #result nvarchar(500) -- this one should return string.
set #variable1 = (SELECT COUNT(*) FROM dbo.Table1 WHERE column1 not in (select column1 from dbo.Table2))
update dbo.Table1 set columnX = 1 where column1 not in (select column1 from dbo.Table2)
set #variable2 = ##ROWCOUNT
and modify your code like this:
SqlParameter result1 = cmd.Parameters.Add("#variable1", SqlDbType.VarChar);
result1.Direction = ParameterDirection.ReturnValue;
SqlParameter result2 = cmd.Parameters.Add("#variable2", SqlDbType.VarChar);
result2.Direction = ParameterDirection.ReturnValue;
ok lets say I did this procedure
ALTER PROCEDURE [dbo].[ProcedureName]
#date NVARCHAR(50),
#result nvarchar(500) output
AS
BEGIN
SET NOCOUNT ON;
DECLARE #variable1 NVARCHAR(50)
set #variable1 = (SELECT COUNT(*) FROM dbo.Table1 WHERE column1 not in (select column1 from Table2))
set #result = #variable1 + ' some text '
i want "#result" to be output text from procedure and get it with C#

SQL Server 2008 R2 stored procedure doesn't work (visual c#)

I have searched and tried different things for the past week or so and my problem is possibly to specific to find an answer through google.
If I execute this query in SQL Server Management Studio and replace the parameter #zoekterm with '%something%', it works fine and returns the result that I want. But when I call the same procedure from C# it returns nothing.
Is this a bug or am I just that stupid?
Here's code of stored procedure and function in C#, (I know I should have used switch case...)
Stored procedure:
-- =============================================
-- Author: Daan
-- Create date:
-- Description:
-- =============================================
ALTER PROCEDURE [dbo].[quick_bedrijf]
-- Add the parameters for the stored procedure here
#zoekterm varchar(100) = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT bedrijf.bedrijf_nr, bedrijf.zoeknaam, bedrijf.plaats
FROM bedrijf
WHERE zoeknaam LIKE #zoekterm AND NIETactief = 0
ORDER BY bedrijf.zoeknaam, bedrijf.plaats
END
C#:
private void snel_zoek2()
{
listView1.Items.Clear();
con.Open();
if (type == 1)
{
command1 = new SqlCommand("quick_project", con);
colnum = 5;
}
else if (type == 2)
{
command1 = new SqlCommand("quick_bedrijf", con);
colnum = 3;
}
else if (type == 3)
{
command1 = new SqlCommand("quick_persoon", con);
colnum = 4;
}
command1.CommandType = CommandType.StoredProcedure;
SqlParameter zoekterm = command1.Parameters.Add("#zoekterm", SqlDbType.VarChar, 100);
zoekterm.Direction = ParameterDirection.Input;
//command1.Parameters.Add(new SqlParameter("#zoekterm", SqlDbType.VarChar)).Value = " '%zee%'";// + textBox2.Text.ToString()+
zoekterm.Value = "'%"+textBox2.Text.ToString()+"%'";
// MessageBox.Show(zoekterm.Value.ToString());
SqlDataAdapter adapt = new SqlDataAdapter();
DataTable dt = new DataTable();
adapt.SelectCommand = command1;
adapt.Fill(dt);
dataGridView1.BindingContext = new BindingContext();
dataGridView1.DataSource = dt;
con.Close();
}
You don't put the quotes into the parameter (those are to signify a literal); it should be:
zoekterm.Value = "%"+textBox2.Text+"%";
It is failing currently because if the text is "abc", it is looking for a string that starts and ends with a single quote and includes "abc". In SQL terms, you were asking it for:
LIKE '''%abc%'''

Categories

Resources