CustomValidator on saving - c#

There is a page (aspx), in it there is a text box (Brand auto) and the button on saving.
It is necessary that if in the Brand of the auto (in textbox) the user specified the following designations and pressed the button to save, shall work the validator and not save.
I created in a DB the table and procedure with these designations:
| ID | Name |
+----+-------+
| 1 | %BM% |
| 2 | %T-3% |
ALTER PROCEDURE [dbo].[vehicle_select]
#mark nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
if exists
(Select Name
From ogpo_specialize_vehicle
where #mark Like Name)
Select 1 as Vle
else
select 0 as Vle
END
I created QueriesAdapter.
Code:
protected void Mark_Validate(object source, ServerValidateEventArgs e)
{
(new DataSetVehiclesTableAdapters.QueriesTableAdapter()).ogpo_specialize_vehicle_select(Mark);
if(dt.VleColumn == 1 )
{
e.IsValid = false;
}
else
{
e.IsValid = true;
}}
Help what to write in a condition? Conditions the wrong

in stored procedure add one more parameter: #Vle int;
Instead of SELECT 1 as Vle use Set #VLE = 1
The same thing for 0.
In code behind:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConnectionName"].ConnectionString;
SqlCommand cmd = new SqlCommand("procedure_name", con);
cmd.Parameters.Add("#mark", SqlDbType.NVarChar).Value = your_value;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
string result = cmd.Parameters["Vle"].Value.ToString();
con.Close();

Code:
protected void Mark_ServerValidate(object source, ServerValidateEventArgs args)
{
DataSetVehicles1TableAdapters.QueriesTableAdapter ds = new DataSetVehicles1TableAdapters.QueriesTableAdapter();
string mark = args.Value;
string result = ds.ogpo_specialize_vehicle_select(mark.ToUpper()).ToString();
if (result == "0")
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}

Related

Issues in insert function in SQL Server and C#

C#:
protected void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection(); {
SqlCommand com = new SqlCommand("sp_studentresult", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", textstudentid.Text);
com.Parameters.AddWithValue("#id_student", textstudentid.Text.Trim());
SqlParameter retval = new SqlParameter("#output", SqlDbType.VarChar, 50);
com.Parameters.AddWithValue("#tamil", txttamil.Text.Trim());
com.Parameters.AddWithValue("#english", txtenglish.Text.Trim());
com.Parameters.AddWithValue("#maths", txtmaths.Text.Trim());
com.Parameters.AddWithValue("#science", txtscience.Text.Trim());
com.Parameters.AddWithValue("#socialScience", txtsocialscience.Text.Trim());
retval.Direction = ParameterDirection.Output;
com.Parameters.Add(retval);
com.ExecuteNonQuery();
string Output = retval.Value.ToString();
textstudentid.Text = string.Empty;
txttamil.Text = string.Empty;
txtenglish.Text = string.Empty;
txtmaths.Text = string.Empty;
txtscience.Text = string.Empty;
txtsocialscience.Text = string.Empty;
SqlDataAdapter adp = new SqlDataAdapter(com);
DataSet ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
tblid.Visible = true;
txtid.Text = ds.Tables[0].Rows[0]["id"].ToString();
txttamil.Text = ds.Tables[0].Rows[0]["Tamil"].ToString();
txtenglish.Text = ds.Tables[0].Rows[0]["English"].ToString();
txtmaths.Text = ds.Tables[0].Rows[0]["Maths"].ToString();
txtscience.Text = ds.Tables[0].Rows[0]["Science"].ToString();
txtsocialscience.Text = ds.Tables[0].Rows[0]["SocialScience"].ToString();
}
else
{
tblid.Visible = false;
output.Text = Output;
}
}
What I have done:
Step 1
When I enter invalid id (which means id doesnot contain in student table) and search, it shows "doesn't exist".
Step 2
When I enter valid id (which means id contains in student and also contain in studentresult table) and search, it shows student marks, if I want to edit the marks and update, so it shows "marks updated".
Step 3
But when I enter id (which means id contains in student but doesn't contain in studentresult table) and search, it works updated function again with all the textboxes contains 0, instead it works insertion.
May I know, what my mistake in the above code?
Can anyone guide me?
I'm struggling for an hour, I'm beginner in .net.
Thanks,
sp_studentresult is broken: it should not insert into studentresult if there already is a row for the given id. Just add
AND NOT EXISTS (SELECT * FROM studentresult WHERE id_student=#id_student)
to
ELSE IF EXISTS (SELECT * FROM student WHERE id=#id_student)
Resulting to:
ALTER PROCEDURE sp_studentresult
(
#id int,
#output varchar(50) output,
#id_student varchar(50),
#Tamil Varchar (100),
#English varchar (50),
#Maths Varchar (50),
#Science Varchar (50),
#SocialScience Varchar (50)
)
AS
IF NOT EXISTS (SELECT * FROM student WHERE id=#id_student)
BEGIN
SET #output='Doesn not EXIST'
END
ELSE IF EXISTS (SELECT * FROM student WHERE id=#id_student)
AND NOT EXISTS (SELECT * FROM studentresult WHERE id_student=#id_student)
BEGIN
INSERT into studentresult (id_student,Tamil,English,Maths,Science,SocialScience) values (#id_student,#Tamil,#English,#Maths,#Science,#SocialScience)
SET #output='Inserted'
END
SELECT * from studentresult where id_student=#id

Updating rows on a table with condition

I'm trying to delete all the rows, starting from the bottom of the table using a condition, but when that conditions is met then i want it to stop updating the table and leave the rest as it was. Example, if the last entry on the table meets it, delete it, if the one after it does not meet the condition then stop there, and exite the loop.
Here's the code i got, but its deleting all the rows :
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("A atualizar dados");
bool check = true;
do
{
string connectionString = #"Data Source=.\wintouch;Initial Catalog=bbl;User ID=sa;Password=Pa$$w0rd";
string queryString = string.Empty;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
queryString = "DELETE FROM wgcdoccab
WHERE serie ='1' AND tipodoc ='FSS'
AND contribuinte ='999999990'
and datadoc = CONVERT(varchar(10),(dateadd(dd, -2, getdate())),120)"
SqlCommand command = new SqlCommand(queryString, connection);
//command.Connection.Open();
command.ExecuteNonQuery();
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
queryString = "SELECT * FROM wgcdoccab
WHERE serie !='1' and tipodoc !='FSS'
and contribuinte !='999999990'
and datadoc != CONVERT(varchar(10),(dateadd(dd, -1, getdate())),120) ";
using (SqlCommand command = new SqlCommand(queryString, connection))
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
check = true;
}
else
{
check = false;
MessageBox.Show("Dados Apagados com sucesso");
}
command.Connection.Close();
}
}
}
while (check);
Try something like this example:
DELETE
FROM tableName
WHERE ID >
(
SELECT MAX(ID)
FROM tableName
WHERE condition = false
)
For example, if you want to delete until a value is 4:
DELETE
FROM tableName
WHERE ID >
(
SELECT MAX(ID)
FROM tableName
WHERE tableName.Value = 4
)
If the table rows are:
|ID|Value|
| 1| 7|
| 2| 4|
Then the subselect will be 2 and no rows will be deleted. However, if the rows are:
|ID|Value|
| 1| 7|
| 2| 4|
| 3| 9|
| 4| 1|
Then the subselect will still return the ID of 2, and the last 2 rows will be deleted.

Error adding from database to dropdownlist

I have a panel that is visible only when the Edit button from GridView is clicked.
In that panel is a form with a DropDownList and a TextBox where you can write a number and add it to a ListBox.
After all the numbers wanted are added to the ListBox when I click the button Finalize is adding to the database the data. In Gridview I have the name concatenate from database , because I have Lastname and Firstname separately.
To be more easy I chose to add from database in DropDownList when I click on Edit button with the specific ID.
When Edit button is clicked this error is showing:
Operation is not valid due to the current state of the object.
In the line where I add in DropDownList. I verified the names of my database, of my table , all and is correct. I even tried only with firstname , not concatenate and it does the same error. I don't know what is wrong. I hope you can help me. This is the code where the error appears.
protected void btnEditSO_Click(object sender, EventArgs e)
{
panelSO.Visible = true;
btnFinalizeSO.Text = " Update ";
Button but = (Button)sender;
GridViewRow grid = (GridViewRow)but.NamingContainer;
string select_sql_SOddl = "SELECT ID, (LASTNAMER | | ' ' | | FIRSTNAMER ) AS REFERENTNAME FROM REFERENT_SHIPPING WHERE ID=" + grid.Cells[14].Text;
using (OracleConnection con = new OracleConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString()))
{
con.Open();
OracleCommand cmd1 = new OracleCommand(select_sql_SOddl, con);
OracleDataReader dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{
ddlReferentShip.Items.Add(dr[0].ToString());
// ddlReferentShip.Items.Add(dr["REFERENTNAME"].ToString());
// ddlReferentShip.DataSource = dr1;
// ddlReferentShip.DataTextField = dr1["REFERENTNAME"].ToString();
// ddlReferentShip.DataValueField = dr1["ID"].ToString();
// ddlReferentShip.DataBind();
}
}
}
You are checking dr1.Read()
and reading dr[0].Tostring()
Also try to clear the list before adding the data. Then the index should be 1 if you need to show the name
it should be
while (dr1.Read())
{
ddlReferentShip.Items.Add(dr1[1].ToString());
}
I guess ID is numeric in query you are passing as .Text
try this
string select_sql_SOddl = "SELECT ID, (LASTNAMER | | ' ' | | FIRSTNAMER ) AS REFERENTNAME
FROM REFERENT_SHIPPING WHERE ID=" + Convert.ToInt32(grid.Cells[14].Text);
also all ways try to use parameterized query to avoide SQL INJECTION
Why you set ddl item from dr when you have dr1 as datareader.
Maybe you can try this:
protected void btnEditSO_Click(object sender, EventArgs e)
{
panelSO.Visible = true;
btnFinalizeSO.Text = " Update ";
Button but = (Button)sender;
GridViewRow grid = (GridViewRow)but.NamingContainer;
string select_sql_SOddl = "SELECT ID, (LASTNAMER | | ' ' | | FIRSTNAMER ) AS REFERENTNAME FROM REFERENT_SHIPPING WHERE ID=" + grid.Cells[14].Text;
using (OracleConnection con = new OracleConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString()))
{
con.Open();
OracleCommand cmd = new OracleCommand(select_sql_SO, con);
OracleCommand cmd1 = new OracleCommand(select_sql_SOddl, con);
OracleDataReader dr = cmd.ExecuteReader();
OracleDataReader dr1 = cmd1.ExecuteReader();
int i=0;
while (dr1.Read())
{
ddlReferentShip.Items.Add(dr1[1].ToString());
i++;
// ddlReferentShip.Items.Add(dr["REFERENTNAME"].ToString());
// ddlReferentShip.DataSource = dr1;
// ddlReferentShip.DataTextField = dr1["REFERENTNAME"].ToString();
// ddlReferentShip.DataValueField = dr1["ID"].ToString();
// ddlReferentShip.DataBind();
}
}
}

Filling a grid view with data of a table where one of the columns=one of the columns in a list

I have a list with two columns in it: ID; int, Score: Double.
In addition, I have a table in SQL SERVER with several columns.One of them is id:int.
I want to have a query like below:
select * from tbl where id = id s in my list.
My codes are below:
protected void btnfind_Click(object sender, EventArgs e)
{
List<KeyValuePair<int, double>> candidatelist = CalculateScores();
FinalMatch(candidatelist);
BindGrid(cmd2);//Contains codes for filling grid view with cmd2 , sql data reader
}
protected void FinalMatch(List<KeyValuePair<int, double>> finallist)
{
DataTable tvp = new DataTable();
tvp = ConvertToDatatable(finallist);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.CommandText = "dbo.DoSomethingWithCandidates";
SqlParameter tvparam = cmd2.Parameters.AddWithValue("#List", tvp);
tvparam.SqlDbType = SqlDbType.Structured;
cmd2.Connection = ClsDataBase.con;
}
protected DataTable ConvertToDatatable(List<KeyValuePair<int, double>> finallist)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Score");
foreach (var item in finallist)
{
var row = dt.NewRow();
row["ID"] = item.Key;
row["Score"] = item.Value;
dt.Rows.Add(row);
}
return dt;
}
protected void BindGrid(SqlCommand cmd)
{
if (ClsDataBase.con.State == ConnectionState.Closed)
ClsDataBase.con.Open();
SqlDataReader dr1 = cmd.ExecuteReader();
try
{
if (dr1.HasRows)
{
gv_allresults.DataSource = dr1;
gv_allresults.DataBind();
}
else
{
Response.Write("<script LANGUAGE='JavaScript' >alert('No Match')</script>");
}
if (dr1.IsClosed == false) dr1.Close();
}
catch (SqlException ex)
{
Response.Write("<script language='javascript'>alert(\"" + ex.ToString() + "\")</script>");
}
catch (Exception ex)
{
Response.Write("<script language='javascript'>alert(\"" + ex.ToString() + "\")</script>");
}
finally
{
ClsDataBase.con.Close();
}
}
And my codes in SQL server are:
CREATE TYPE dbo.CandidateList
AS TABLE
(
ID INT,
Score FLOAT
);
GO
CREATE PROCEDURE dbo.DoSomethingWithCandidates
#List AS dbo.CandidateList READONLY
AS
BEGIN
SET NOCOUNT ON;
SELECT ID FROM #List;
END
GO
I don't get the result. My procedure's codes are not complete. I don`t know what to do. Please help me.
Thanks so much.
Edited codes according to given suggestion:
protected void FinalMatch(List<KeyValuePair<int, double>> finallist)
{
int[] canArr = finallist.Select(x => x.Key).ToArray();
string csv = string.Join(",", canArr);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.CommandText = "dbo.ReturnCandidates";
cmd2.Parameters.AddWithValue("#LIST", csv);
cmd2.Connection = ClsDataBase.con;
}
And new codes in Sql server are:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[CSVToTable] (#InStr VARCHAR(MAX))
RETURNS #TempTab TABLE
(id int not null)
AS
BEGIN
;-- Ensure input ends with comma
SET #InStr = REPLACE(#InStr + ',', ',,', ',')
DECLARE #SP INT
DECLARE #VALUE VARCHAR(1000)
WHILE PATINDEX('%,%', #INSTR ) <> 0
BEGIN
SELECT #SP = PATINDEX('%,%',#INSTR)
SELECT #VALUE = LEFT(#INSTR , #SP - 1)
SELECT #INSTR = STUFF(#INSTR, 1, #SP, '')
INSERT INTO #TempTab(id) VALUES (#VALUE)
END
RETURN
END
GO
CREATE PROCEDURE dbo.ReturnCandidates
(
#LIST VARCHAR(200)
)
AS
BEGIN
SELECT *
FROM tblspecifications
WHERE id IN ( SELECT * FROM dbo.CSVToTable(#LIST) )
END
I get this error: "Procedure or function ReturnCandidates has too many arguments specified",
In below line:
SqlDataReader dr1 = cmd.ExecuteReader();
Please help me. Thanks a lot
I see cmd2.ExecuteNonQuery() missing.
Also, why not make a comma separated list of ID's and then send it to the SQL function. Example
int[] canArr= candidatelist.Select(x => x.Key).ToArray();
string csv = string.Join(",", canArr);
EDIT:
I created a SQL Fiddle for your query. It works.
http://sqlfiddle.com/#!6/c3d013/1/1

Reference data in SQLDataReader by column and rows or any alternative

I am running a stored procedure and the result is this format
+------+--------+-----+-------+
| ID | Resign | Sum | Count |
+------+--------+-----+-------+
| 1234 | 0 | 400 | 3 |
| 1234 | 1 | 800 | 4 |
+------+--------+-----+-------+
I tried this code to reference the values returned by the query but, it seem not working the way I want it
if (conn.State != ConnectionState.Open)
conn.Open();
SqlCommand sc = new SqlCommand();
sc.CommandText = "usp_GetResignPool";
sc.CommandType = CommandType.StoredProcedure;
sc.Connection = conn;
sc.Parameters.Add(AddParam(EndDate, "#EndDate"));
sc.Parameters.Add(AddParam(am_id, "#id"));
SqlDataReader reader;
reader = sc.ExecuteReader();
while (reader.Read())
{
if reader. // lost here
}
How can I do something like this. ↓
int resigned = 0, resign_count = 0, not_resigned = 0, notresign_count =0;
if (read["Resigned"] == 1)
{
resigned = read["sum"];
resign_count = read["count"];
}
else
{
not_resigned = read["sum"];
notresign_count = read["count"];
}
It is not important that I used SQLDataReader.
Edit: Real column names
ID Resigned sum count
--------- ----------- ---------------------- -----------
It didn't work because you don't have a column in your table named "Resigned", like you have when you are working with your SqlDataReader.
EDIT: I think the root of the problem is the way you are adding parameters. AddParam() is not the method you want to be using. Therefore, your result set is probably empty.
....
SqlCommand sc = new SqlCommand();
sc.CommandText = "usp_GetResignPool";
sc.CommandType = CommandType.StoredProcedure;
sc.Connection = conn;
sc.Parameters.AddWithValue("#EndDate", EndDate);
sc.Parameters.AddWithValue("id", am_id);
SqlDataReader reader;
reader = sc.ExecuteReader();
using (reader = sc.ExecuteReader())
{
while (reader.Read())
{
if (Convert.ToInt32(read["Resign"]) == 1)
{
resigned = Convert.ToInt32(read["Sum"]);
resign_count = Convert.ToInt32(read["Count"]);
}
else
{
not_resigned = Convert.ToInt32(read["Sum"]);
notresign_count = Convert.ToInt32(read["Count"]);
}
}
}
Notice how I changed your element indicator to "Resign". This needs to match the column that is returned in your dataset. Or, you could use a column number to get this, like so:
if (Convert.ToInt32(read[1]) == 1)
{
resigned = Convert.ToInt32(read[2]);
resign_count = read[3];
}
else
{
not_resigned = Convert.ToInt32(read[2]);
notresign_count = Convert.ToInt32(read[3]);
}
Also, keep in my that in every iteration or your while loop, you'll be overwriting the variables resigned, resign_count or not_resigned and notresign_count.
Would this work?
int resign = 0;
int not_resign = 0;
int resign_count = 0;
int not_resign_count = 0;
while (reader.Read())
{
if (Convert.ToInt32(reader["Resigned"]) == 1)
{
resign = Convert.ToInt32(reader["Sum"]);
resign_count = Convert.ToInt32(reader["Count"]);
}
else
{
not_resign = Convert.ToInt32(reader["Sum"]);
not_resign_count = Convert.ToInt32(reader["Count"]);
}
}
Can you post your query from the procedure?
Are the column names really "Sum" and "Count"?
There are reserved words, maybe you should try using "AS" and give other names to these to columns in the projection.

Categories