I have a search button on my web page and it should return the subject name from the DB which are similar to entered search word, but I didnt get any out put when I use the following code... please help me to do it...
this is my C# code
protected void Button1_Click(object sender, ImageClickEventArgs e)
{
MySqlConnection connection = new MySqlConnection("server=localhost; database=e-learningsystem; uid=root; password=123;port=3307;");
connection.Open();
string srh = editbox_search.Type;
try
{
MySqlCommand cmd = new MySqlCommand("SELECT * FROM subject WHERE Name= LIKE %'" + srh + "'%", connection);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
connection.Close();
}
catch
{
}
asp.net code:
<input name="editbox_search" class="editbox_search" id="editbox_search"
maxlength="80" type="text"
style="background-color: #99CCFF; margin-top: 0px; height: 15px;" runat="server"
enableviewstate="True" title="Search Courses:" clientidmode="Inherit"
dir="ltr" visible="True"/>
<asp:Button ID="Button1"
runat="server" Height="26px" Text="Go" Width="32px" />
<asp:GridView ID="GridView1" runat="server" ShowFooter="True"
Caption="<h3 style='background-color:teal;color:white;'>Search Results...</h3>"
BackColor="LightGoldenrodYellow" BorderColor="Tan"
BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None">
</asp:GridView>
There is Mistake in Your Query, Correct it as below.
MySqlCommand cmd = new MySqlCommand("SELECT * FROM subject WHERE Name LIKE '%" + srh + "%'", connection);
First, use a parameterized command to avoid SQL injections. Second, I think the value you are looking for is in the Text property of the input, not the Type property. Lastly, the single quotes go outside the matching characters, i.e., '%searchvalue%'.
protected void Button1_Click(object sender, ImageClickEventArgs e)
{
MySqlConnection connection = new MySqlConnection("connection string removed");
connection.Open();
try
{
var cmd = new MySqlCommand("SELECT * FROM subject WHERE Name LIKE '%#input%'", connection);
cmd.Parameters.Add("#input", editbox_search.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
connection.Close();
}
catch (Exception e)
{
// log the exception
}
}
Try this one:
protected void Button1_Click(object sender, ImageClickEventArgs e)
{
MySqlConnection connection = new MySqlConnection("connection string removed");
connection.Open();
try
{
var cmd = new MySqlCommand("SELECT * FROM subject WHERE Name LIKE '%'+#input+'%'", connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#input", editbox_search.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
MySqlDataReader dr = cmd.ExecuteReader();
da.Fill(dr);
GridView1.DataSource = dr;
GridView1.DataBind();
connection.Close();
}
catch (Exception e)
{
// log the exception
}
}
Try this query
SELECT * FROM subject WHERE Name LIKE %'" + srh + "'%
Related
public partial class _Default : System.Web.UI.Page
{
protected void submit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data source= LAPTOP-6\\SQLEXPRESS;Initial Catalog=training;integrated Security=true";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Sp_PO";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#date1", TextBox1.Text.ToString());
cmd.Parameters.AddWithValue("#date2", TextBox2.Text.ToString());
cmd.Connection = con;
try
{
con.Open();
GridView1.EmptyDataText = "No Records Found";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception ex)
{
lblerror.Text = ex.Message.ToString();
}
finally
{
con.Close();
con.Dispose();
}
}
}
How to give paging in some sites they have given bind grid but if i used bind grid here i can't run it on submit button?
protected void reset_Click(object sender, EventArgs e)
{
TextBox1.Text = string.Empty;
TextBox2.Text = string.Empty;
}
protected void save_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data source= LAPTOP-6\\SQLEXPRESS;Initial Catalog=training;integrated Security=true";
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox check = (CheckBox)gvr.FindControl("check");
if (check.Checked)
{
conn.Open();
string data1 = ((Label)gvr.FindControl("pomas_pono")).Text;
string data2 = ((Label)gvr.FindControl("pomas_suppliercode")).Text;
string data3 = ((Label)gvr.FindControl("pomas_pobasicvalue")).Text;
string data4 = ((Label)gvr.FindControl("poitm_itemcode")).Text;
string data5 = ((Label)gvr.FindControl("poitm_order_quantity")).Text;
string data6 = ((Label)gvr.FindControl("poitm_itemvalue")).Text;
string data7 = ((Label)gvr.FindControl("poitm_itemdescription")).Text;
string data8 = ((TextBox)gvr.FindControl("remarks")).Text;
SqlCommand command = new SqlCommand("INSERT INTO po_remarks" + "(pomas_pono,pomas_suppliercode,pomas_pobasicvalue,poitm_itemcode,poitm_order_quantity,poitm_itemvalue,poitm_itemdescription,remarks) VALUES(#pomas_pono,#pomas_suppliercode,#pomas_pobasicvalue,#poitm_itemcode,#poitm_order_quantity,#poitm_itemvalue,#poitm_itemdescription,#remarks)", conn); //generate insert sql using above data
command.Parameters.AddWithValue("#pomas_pono", data1);
command.Parameters.AddWithValue("#pomas_suppliercode", data2);
command.Parameters.AddWithValue("#pomas_pobasicvalue", data3);
command.Parameters.AddWithValue("#poitm_itemcode", data4);
command.Parameters.AddWithValue("#poitm_order_quantity", data5);
command.Parameters.AddWithValue("#poitm_itemvalue", data6);
command.Parameters.AddWithValue("#poitm_itemdescription", data7);
command.Parameters.AddWithValue("#remarks", data8);
command.ExecuteNonQuery();
}
}
conn.Close();
}
protected void cancel_Click(object sender, EventArgs e)
{
Page.Response.Redirect("Default.aspx");
}
The GridView control has a paging option as described here: https://msdn.microsoft.com/en-us/library/aa479347.aspx
<asp:GridView ID=" productsGridView" Runat="server"
DataSourceID="productDataSource" AutoGenerateColumns="False"
AllowSorting="True" BorderWidth="2px" BackColor="White"
GridLines="None" CellPadding="3"
CellSpacing="1" BorderStyle="Ridge" BorderColor="White"
AllowPaging="True" PageSize=50>
Notice the property of: AllowPaging. You can specify the number of records per page using the PageSize property. I think the default PageSize is: 10.
You can also specify the properties programmatically e.g.
GridView1.AllowPaging=true;
GridView1.PageSize=50;
protected void submit_Click(object sender, EventArgs e)
{
BindGrid();
}
protected void BindGrid()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data source= LAPTOP-6\\SQLEXPRESS;Initial Catalog=training;integrated Security=true";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Sp_PO";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
try
{
con.Open();
GridView1.EmptyDataText = "No Records Found";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
}
C# code
public partial class photorecognize : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\registerdatabase.mdf;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select image from [picture] where username = 'wenhao123'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
DataListABC.DataSource = dt;
DataListABC.DataBind();
con.Close();
}
}
asp.net
<asp:DataList ID="DataListABC" runat="server" Height="208px" Width="226px">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" />
</ItemTemplate>
</asp:DataList>
Database:
I am trying to bind a selected item from the database in dropdownlist. I am not getting the users selected data in the dropdownlist instead it loads everything. What i need is to have a default selected value from the database along with other items. Please help me to overcome this problem. Thanking you in advance.
Stored procedure:
CREATE PROCEDURE [dbo].[get_student_details]
#StudentId int = 0
AS
BEGIN
SET NOCOUNT ON;
SELECT
dbo.Student.InstituteId,
dbo.Student.Institute,
dbo.Student.Name,
dbo.Student.Gender,
dbo.Student.Age
FROM
dbo.Student
WHERE
dbo.Student.StudentId = #StudentId
END
My .aspx markup:
<asp:DropDownList ID="ddlInstitute" runat="server"></asp:DropDownList>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtGender" runat="server"></asp:TextBox>
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
<asp:Button ID="btnPersonalDetails" runat="server" Text="Search" OnClick="GetStudentDetails"/>
My code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillInstitute();
}
}
public void FillInstitute()
{
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "get_Institute";
cmd.Connection = con;
try
{
con.Open();
ddlInstitute.DataSource = cmd.ExecuteReader();
ddlInstitute.DataTextField = "Institute";
ddlInstitute.DataValueField = "InstituteId";
ddlInstitute.DataBind();
ddlInstitute.Items.Insert(0, new ListItem("--Select--", "0"));
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
public void GetStudentDetails()
{
studentid= 123;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "get_student_details";
cmd.Parameters.Add("#StudentId", SqlDbType.Int).Value = studentid;
cmd.Connection = con;
try
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
ddlInstitute.DataValueField= dr["InstituteId"].ToString();
ddlInstitute.DataTextField= dr["Institute"].ToString();
txtName.Text = dr["Name"].ToString();
txtGender.Text = dr["Gender"].ToString();
txtAge.Text = dr["Age"].ToString();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
You have to use SelectedValue property of DropDownList.DataTextField and DataValueField are for specifying which properties from DataSource should be used as Text and Value of drop down list.
Replace these lines:
ddlInstitute.DataValueField= dr["InstituteId"].ToString();
ddlInstitute.DataTextField= dr["Institute"].ToString();
with:
ddlInstitute.SelectedValue= dr["InstituteId"].ToString();
or you can also do:
ddlInstitute.Items.FindByValue(dr["InstituteId"].ToString()).Selected = true;
You can also refer this article
Assuming you know which ID you want to have selected, try something like this:
ddlInstitute.Items.FindByValue(dr["InstituteId"].ToString()).Selected = true;
Try it as a function:
void FN_loadBranch()
{
classname cls = new classname ();
DataTable dt = new DataTable();
dt = cls.FUNCTIONNAMEINCLASS(int id);
dropdown.DataSource = dt;
dropdown.DataValueField = "valuefield";
dropdown.DataTextField = "textfield";
dropdown.DataBind();
ddlBranch.Items.Insert(0, new ListItem("--Select--", "0"));
}
In function:
public DataTable FUNCTIONNAMEINCLASS( int id)
{
try
{
using (SqlConnection cn = new SqlConnection(CLASS.ConnectionString))
{
SqlCommand cmd = new SqlCommand("[storedprocedure]", cn);
cn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ID", SqlDbType.VarChar, 50).Value = id;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
Use stored procedure in the function
I have four text boxes whose value I need to change based on the selection in a dropdown list. but when I change the value, the textboxes don't update
My codes:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
DataSourceID="Employees" DataTextField="FullName" DataValueField="FullName"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="Employees" runat="server"
ConnectionString="<%$ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT [FullName] FROM [Employees] ORDER BY [FirstName]">
</asp:SqlDataSource>
And class file:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string cn = "Data Source=.;Initial Catalog=DBRE ;Integrated Security=True";
SqlConnection scon = new SqlConnection(cn);
SqlCommand scmd = new SqlCommand("Select * from Employees where FullName = '" + DropDownList1.SelectedItem.Value + "'", scon);
SqlDataReader sdr;
try
{
scon.Open();
sdr = scmd.ExecuteReader();
txtName.Text = sdr["FirstName"].ToString();
txtSurname.Text = sdr["LastName"].ToString();
txtDepartment.Text=sdr["Dept"].ToString();
txtCostCentre.Text=sdr["CostCentre"].ToString();
}
catch (Exception ex)
{
}
finally
{
scon.Close();
}
What am i doing wrong here?
May be i think check the exception, Use Reader like or use ExecuteScalar
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
}
}
Check this
dynamically filled DropDownList does not retain value on postback ASP.net c#
Try EnableViewState="true"
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" EnableViewState="true" DataSourceID="Employees" DataTextField="FullName" DataValueField="FullName"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Set your dropdownlist with AutoPostBack="true" with the on selected index changed like this:
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlPNo_selectedChanged" ></asp:DropDownList>
And in your code behind load data into your dropdownlist with the following code:
String conn = System.Configuration.ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection(conn);
SqlDataAdapter da = new SqlDataAdapter("select Code from table1", con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
con.Close();
ddl.DataSource = ds.Tables[0];
ddl.DataValueField = "Code";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("-- select --"));
}
}
Now you can bind data on dropdownlist changed with the following code:
protected void ddl_selectedChanged(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
String strQuery = "select description from table1 where Code = #Code";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#Code", ddl.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtbdescription.Text = dr["description"].ToString();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
where txtbdescription is the id of your textbox.
Hope this will help.
Remove AutoPostBack="True"
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="Employees" DataTextField="FullName" DataValueField="FullName"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
And add if (!ispostback) condition
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!isPostback)
{
string cn = "Data Source=.;Initial Catalog=DBRE ;Integrated Security=True";
SqlConnection scon = new SqlConnection(cn);
SqlCommand scmd = new SqlCommand("Select * from Employees where FullName = '" + DropDownList1.SelectedItem.Value + "'", scon);
SqlDataReader sdr;
try
{
scon.Open();
sdr = scmd.ExecuteReader();
txtName.Text = sdr["FirstName"].ToString();
txtSurname.Text = sdr["LastName"].ToString();
txtDepartment.Text=sdr["Dept"].ToString();
txtCostCentre.Text=sdr["CostCentre"].ToString();
}
catch (Exception ex)
{
}
finally
{
scon.Close();
}
}
}
How do I load data into combobox from database? I want to display the supportID into the combobox in the form. the code I am using is pasted here. I am calling BindData() in the formload. Ia m getting exception as: Cannot bind to the new display member.
Parameter name: newDisplayMember. the code I used is:
public void BindData()
{
SqlConnection con = new SqlConnection(#"server=RSTT2; database = Project ; User Id=sa; Password=PeaTeaCee5#");
con.Open();
string strCmd = "select supportID from Support";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
cbSupportID.DataSource = ds;
cbSupportID.DisplayMember = "supportID";
cbSupportID.ValueMember = "supportID";
cbSupportID.Enabled = true;
cmd.ExecuteNonQuery();
con.Close();
}
The DataSource for your combobox should be a DataTable in this case, try this:
cbSupportID.DataSource = ds.Tables[0];
Or better, you should fill data into a DataTable instead of a DataSet like this:
DataTable dt = new DataTable();
da.Fill(dt);
//...
cbSupportID.DataSource = dt;
public void BindData()
{
SqlConnection con = new SqlConnection(#"server=RSTT2; database = Project ; User Id=sa; Password=PeaTeaCee5#");
con.Open();
string strCmd = "select supportID from Support";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
con.Close();
cbSupportID.DisplayMember = "supportID";
cbSupportID.ValueMember = "supportID";
cbSupportID.DataSource = ds;
cbSupportID.Enabled = true;
}
I hope this helps.
Follow this example:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace ComboBoxData
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string conStr = #"Server =.\SQLEXPRESS2014; Database=NORTHWND; User Id=sa; Password=******";
SqlConnection conn = new SqlConnection(conStr);
DataSet ds = new DataSet();
string getEmpSQL = "SELECT E.LastName FROM dbo.Employees E;";
SqlDataAdapter sda = new SqlDataAdapter(getEmpSQL, conn);
try
{
conn.Open();
sda.Fill(ds);
}catch(SqlException se)
{
MessageBox.Show("An error occured while connecting to database" + se.ToString());
}
finally
{
conn.Close();
}
comboBox1.DataSource = ds.Tables[0];
comboBox1.DisplayMember = ds.Tables[0].Columns[0].ToString();
}
}
}
CmbDefaultPrinter.DisplayMember = "[table fieldname]";
CmbDefaultPrinter.ValueMember = "[table fieldname]";
CmbDefaultPrinter.DataSource = ds.Tables[0];
CmbDefaultPrinter.Enabled = true;
Mention the Column Name in DataField which you want to load.
and in aspx.cs in page load bind the gridview.
enter code here
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="User_Group" HeaderText="UserName" ItemStyle
Width="150px" />