I have a problem doing search in asp.net, when I try to run the code in sqlserver or using query buider it works fine. But when I run the program in browser, the gridview didn't even show up. Help plz.
protected void btnsearchadvance_Click(object sender, EventArgs e)
{
if (txtname.Text.Trim() != "")
{
search = "NmBengkel LIKE '%" + txtname.Text + "%'";
}
if (txtaddress.Text.Trim() != "")
{
search = search + " AND Address LIKE '%" + txtaddress.Text + "%'";
}
if (txttelp.Text.Trim() != "")
{
search = search + " AND NoTelp LIKE '%" + txttelp.Text + "%'";
}
if (txtnote.Text.Trim() != "")
{
search = search + " AND Note LIKE '%" + txtnote.Text + "%'";
}
SqlDataSource1.SelectCommand = "SELECT * FROM mst_bengkel where " + search;
}
you can use parameterized Query like
_cmd = new SqlCommand();
_cmd.CommandText = "prc_GetSampleData";
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add("#name", SqlDbType.Varchar).Value = txtname.Text.Trim();
_cmd.Parameters.Add("#address", SqlDbType.Decimal).Value = txtaddress.Text.Trim();
_cmd.Parameters.Add("#telp", SqlDbType.Decimal).Value = txttelp.Text.Trim();
_cmd.Parameters.Add("#note", SqlDbType.Decimal).Value = txtnote.Text.Trim();
_cmd.Connection = _con;
_con.Open();
try
{
sqlDA = new SqlDataAdapter(sqlCmd);
sqlDA.Fill(ds, "SampleData");
}
catch (Exception ex) { _ex = ex; }
finally { if (_con.State == ConnectionState.Open) { _con.Close(); } }
Here is the procedure
Create procedure prc_GetSampleData
#name varchar(50) =null,
#address varchar(50)=null,
#telp varchar(50)=null,
#note varchar(50)=null
AS
BEGIN
Declare #prmname varchar(50)='%%'
Declare #prmaddress varchar(50)='%%'
Declare #prmtelp varchar(50)='%%'
Declare #prmnote varchar(50)='%%'
if #name is not null
begin
set #prmname=#name
end
if #address is not null
begin
set #prmaddress=#address
end
if #telp is not null
begin
set #prmtelp=#telp
end
if #note is not null
begin
set #prmnote=#note
end
SELECT * FROM mst_bengkel where name Like #prmname and address like #prmaddress and telp like #prmtelp and note like #prmnote
END
Use stored procedure.
using System.Data;
using System.Data.SqlClient;
#region Declaration
private SqlConnection _con;
private SqlCommand _cmd;
private SqlDataAdapter _sda;
private Exception _ex;
private SqlDataReader _sdr;
#endregion
protected void btnsearchadvance_Click(object sender, EventArgs e)
{
_con = new SqlConnection(ConfigurationManager.AppSettings["connectionstring"].ToString());
_cmd = new SqlCommand();
_cmd.CommandText = "prc_GetSampleData";
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add("#name", SqlDbType.Varchar).Value = txtname.Text.Trim();
_cmd.Parameters.Add("#address", SqlDbType.Decimal).Value = txtaddress.Text.Trim();
_cmd.Parameters.Add("#telp", SqlDbType.Decimal).Value = txttelp.Text.Trim();
_cmd.Parameters.Add("#note", SqlDbType.Decimal).Value = txtnote.Text.Trim();
_cmd.Connection = _con;
_con.Open();
try
{
_sda = new SqlDataAdapter(_cmd);
_sda.Fill(ds, "SampleData");
}
catch (Exception ex) { _ex = ex; }
finally { if (_con.State == ConnectionState.Open) { _con.Close(); } }
}
Related
I have a small ASP.NET registration page linked to a database. If the user enters the username that already exists in the database, then it should display "user already exists", but it is not doing that:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string check = "Select Count(*) from Registration where UserName = '"+TextBoxUN.Text+"';";
SqlCommand comm = new SqlCommand(check, conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already exists!!");
}
conn.Close();
}
}
protected void Button3_Click(object sender, EventArgs e)
{
if (this.DropDownListCountry.SelectedValue == "-Select-" && this.DropDownListAge.SelectedValue == "-Select-")
{
Response.Write("Select Country and age!");
}
else if(this.DropDownListCountry.SelectedValue == "-Select-" && this.DropDownListAge.SelectedValue != "-Select-")
{
Response.Write("Select Country!");
}
else if (this.DropDownListCountry.SelectedValue != "-Select-" && this.DropDownListAge.SelectedValue == "-Select-")
{
Response.Write("Select Age!");
}
else
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQ = "insert into Registration(UserName,Email,Password,Country,Age) values ('" + TextBoxUN.Text + "','" + TextBoxEmail.Text + "','" + TextBoxPass.Text + "','" + DropDownListCountry.SelectedItem.ToString() + "','" + DropDownListAge.SelectedItem.ToString() + "');";
SqlCommand comm = new SqlCommand(insertQ, conn);
comm.ExecuteNonQuery();
Response.Redirect("Display.aspx");
conn.Close();
}
catch(Exception ex)
{
Response.Write("Error : " + ex.ToString());
}
}
}
}
I think you should try first
If ( temp > 0)
{
}
also debug to see what is returned by the sql query
Few Things.
You need to check this before inserting the data.
You are not preventing entering the same data if the username still exists
You can check top 1 instead of count.
private bool IsUserExists()
{
bool UserExists = false;
SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string check = "Select Count(*) from Registration where UserName = '"+TextBoxUN.Text+"';";
SqlCommand comm = new SqlCommand(check, conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if (temp >= 1)
{
UserExists = true;
Response.Write("User already exists!!");
}
conn.Close();
}
return UserExists ;
}
Check this before inserting the data.
try
{
if(UserExists())
return; //Skips further code when user exists.
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQ = "insert into Registration(UserName,Email,Password,Country,Age) values ('" + TextBoxUN.Text + "','" + TextBoxEmail.Text + "','" + TextBoxPass.Text + "','" + DropDownListCountry.SelectedItem.ToString() + "','" + DropDownListAge.SelectedItem.ToString() + "');";
SqlCommand comm = new SqlCommand(insertQ, conn);
comm.ExecuteNonQuery();
Response.Redirect("Display.aspx");
conn.Close();
}
catch(Exception ex)
{
Response.Write("Error : " + ex.ToString());
}
I have a ASP.NET page which have details in below manner.
Date OfficerID DutyID
25-NOV-13 2 666
26-NOV-13 2 666
27-NOV-13 2 666
28-NOV-13 2 666
29-NOV-13 2 666
30-NOV-13 2 666
01-DEC-13 2 666
02-DEC-13 2 523
The above is being populated in gridview through below code snippet
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string sqlQuery = "select * from duty_rota where duty_date between sysdate and sysdate+18";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
//DropDownList1.DataSource = table;
//DropDownList1.DataValueField = "";
GridView1.DataSource = table;
GridView1.DataBind();
Now I also have a previous button which should output the same page but with sql query slightly changed
select * from duty_rota where duty_date between sysdate-18 and sysdate;
and with every button click the date parameters should be decreased by 18, i.e with 1st previous button click query will be
sysdate-18 and sysdate
with 2nd click
sysdate-36 and sysdate-18
with 3rd click
sysdate-54 and sysdate-36
and so on...
Please help me how could I acheieve it , I was trying to implement it with a variable associated with Previous buttons button click event which would change with every subsequent click. But I am not really able to accomplish it. Can anybody please guide me on this.
Write below code to handle dynamic query on previous and next button click event :
protected void PrevioseButton_Click(object sender, EventArgs e)
{
var sqlQuery = this.GenerateQuery(false);
this.BindGrid(sqlQuery);
}
protected void NextButton_Click(object sender, EventArgs e)
{
var sqlQuery = this.GenerateQuery(true);
this.BindGrid(sqlQuery);
}
private string GenerateQuery(bool isNext)
{
if (ViewState["fromDate"] == null && ViewState["toDate"] == null)
{
ViewState["fromDate"] = isNext ? "sysdate+18" : "sysdate-18";
ViewState["toDate"] = isNext ? "sysdate+36" : "sysdate";
}
else
{
var from = ViewState["fromDate"].ToString().Replace("sysdate", string.Empty);
var to = ViewState["toDate"].ToString().Replace("sysdate", string.Empty);
int fromDay = 0;
int toDay = 0;
if (from != string.Empty)
{
fromDay = Convert.ToInt32(from);
}
if (to != string.Empty)
{
toDay = Convert.ToInt32(to);
}
if (!isNext)
{
fromDay = fromDay - 18;
toDay = toDay - 18;
}
else
{
fromDay = fromDay + 18;
toDay = toDay + 18;
}
from = "sysdate";
to = "sysdate";
if (fromDay > 0)
{
from += "+" + fromDay;
}
else if (fromDay < 0)
{
from += fromDay.ToString();
}
if (toDay > 0)
{
to += "+" + toDay;
}
else if (toDay < 0)
{
to += toDay.ToString();
}
ViewState["fromDate"] = from;
ViewState["toDate"] = to;
}
var sqlQuery = "select * from duty_rota where duty_date between " + ViewState["fromDate"] + " and "
+ ViewState["toDate"];
return sqlQuery;
}
private void BindGrid(string sqlQuery)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
On the button click event, try this:
DataTable table = new DataTable();
string connectionString = GetConnectionString();
if (Session["sysdate"] == null || string.IsNullOrEmpty(Session["sysdate"].ToString()))
Session["sysdate"] = "-18";
else
Session["sysdate"] = "+ " + (Convert.ToInt32(Session["sysdate"]) - 18).ToString();
string sysdate = Session["sysdate"].ToString();
string sqlQuery = "select * from duty_rota where duty_date between sysdate " + sysdate + " and sysdate+18 " + sysdate;
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
Me thoughts an ObjectDataSource control would perfectly provide you with a solution...however then I realized that your pagesize varies!
In such a case you need to have your pagination to be disassociated with the gridview. Meaning pagination should be separate and your data which needs to be displayed in the grid view need to be separate. They may have something like a master-child relationship. It means you'd need separate db calls for fetching "each".
You pagination part could be rendered by a gridview or a data list view.
However, if the pagesize on the gridview is always constant you need read this: http://www.codeproject.com/Articles/13963/Implement-Paging-using-ObjectDataSource-with-GridV
I want to update multi checkboxlist value to the the database. I already databound my checkboxlist from other table which is the medicine table. Now i want to update my value to consultation table, but i can not
`
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < txtcheckbox.Items.Count - 1; i++)
{
if (txtcheckbox.Items[i].Selected == true)
{
str = str + txtcheckbox.Items[i].Text + ",";
}
}
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
String sql = "UPDATE [consultation] set mname3 = " + str + " WHERE [conid] = #conid";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#conid", txtconid);
cmd.Parameters.AddWithValue("#mname3", str);
int j = cmd.ExecuteNonQuery();
if (j > 0)
{
Label2.Visible = true;
Label2.Text = "Successfully Complete Dispensary";
txtconid.Text = "";
}
else
{
Label2.Visible = true;
Label2.Text = "Not Successfully Complete Dispensary";
txtconid.Text = "";
}
con.Close();
}
catch
{
Label2.Visible = true;
Label2.Text = "Error";
txtconid.Text = "";
}
}
`
I guess you have exception here. Because:
String sql = "UPDATE [consultation] set mname3 = " + str + " WHERE [conid] = #conid";
here you use concatenation of strings and your sql query will look like:
UPDATE [consultation] set mname3 = sometextvale WHERE [conid] = #conid
mname3 have nvarchar sql type I guess, so you need to put string value in qoutes:
String sql = "UPDATE [consultation] set mname3 = ' " + str + " ' WHERE [conid] = #conid";
Or you can use paramaeter for sql query, like you already did for #conid:
String sql = "UPDATE [consultation] set mname3 = #mname3 WHERE [conid] = #conid";
It's better solution in security way.
Some additional comments:
for (int i = 0; i < txtcheckbox.Items.Count - 1; i++)
Are you sure here should be txtcheckbox.Items.Count - 1? You will lost the last one.
And the 2nd one: Mix code for construction and execution query (DAL) in code behind of page with some kind of business logic not a good practice =)
I'm trying to insert data from a form to my database and it is throwing this error:
No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.
Maybe it has to do with the fact that I try to get a data from a dropdownlist and I'm not really sure the syntax is great.
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Movie;Integrated Security=True");
conn.Open();
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", Title);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", GenreDropDown);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", Descreption);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
You -weren't using any of the vars where you had the values
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", titlename);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", genre);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", descp);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
The problem is that you are trying to use the entire textbox as the value to the parameter.
Change:
cmd.Parameters.AddWithValue("Title", Title);
to
cmd.Parameters.AddWithValue("Title", Title.Text);
i have a code performing paging and sorting in grid view.
(bing_grid is user defined function)
public void bind_grid()
{
con = new SqlConnection();
con.ConnectionString = "Data Source=STIRAPC105;InitialCatalog=anitha;Integrated Security=True";
con.Open();
SqlDataAdapter sqa = new SqlDataAdapter("select * from employees", con);
DataSet ds = new DataSet();
sqa.Fill(ds);
DataTable mytab = ds.Tables[0];
GridView1.DataSource = mytab;
GridView1.DataBind();
//con.Close();
}
code for paging
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bind_grid();
}
code for sorting
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = GridView1.DataSource as DataTable;
if (dt != null)
{
DataView dataview = new DataView(dt);
dataview.Sort = e.SortExpression + " " + sort_grid(e.SortDirection);
GridView1.DataSource = dataview;
GridView1.DataBind();
}
}
user defined code for sorting
public string sort_grid()
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
paging works, Errors was:
1. "no overload for method 'sort_grid' takes 1 argument" (dataview.Sort = e.SortExpression + " " + sort_grid(e.SortDirection);)
2.The name 'sortDirection does not exist in the current context. (switch (sortDirection))
Help me friends.
this method:
public string sort_grid()
takes no arguments but you are trying to call it with e.SortDirection:
dataview.Sort = e.SortExpression + " " + sort_grid(e.SortDirection);
You must change the signature of sort_grid() to
sort_grid(SortDirection sortDirection)
This will also solve your second problem, which you are trying to use sortDirection variable, before declaring it in the method sort_grid.