Textboxes dont update when dropdownlist value is changed ASP.NET - c#

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();
}
}
}

Related

How to give paging for grid view from data source without databinding

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();
}

How can I bind AutoCompleteExtender to dynamically created control?

The autofill works for the static text box, but not the dynamic one.
User needs to be able to add as many rows as necessary, and each text box should pull from the same table. There are too many records in the table to use a simple drop down... Any ideas?
This Works
<form id="TestForm" runat="server">
<asp:ScriptManager ID="thisNameDoesntMatter" runat="server"
EnablePageMethods="true" />
<asp:TextBox ID="noteValue" runat="server" OnTextChanged="noteValue_TextChanged" CausesValidation="true" Width="1000"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="searchNoteValues"
MinimumPrefixLength="2"
CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
TargetControlID="noteValue"
ID="AutoCompleteExtenderNoteValues" runat="server" FirstRowSelected="false"/>
</form>
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> searchNoteValues(string prefixText, int count)
{
string strConn = db_connection_string_EINSTEIN;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT id, NoteValue FROM agl.GuidelineNoteValues where isActive = 1 and NoteValue like '%' + #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
con.Open();
List<string> NoteValues = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
NoteValues.Add(sdr["NoteValue"].ToString());
}
}
con.Close();
return NoteValues;
}
This Does Not
<form id="TestForm" runat="server">
<asp:ScriptManager ID="thisNameDoesntMatter" runat="server"
EnablePageMethods="true" />
<asp:PlaceHolder ID="TestPlaceHolder" runat="server" />
<asp:LinkButton ID="TestAddNoteButton" runat="server" Text="Add a note" OnClick="TestAddNoteButton_Click" CausesValidation="false" AutoPostBack="true"/>
</div>
</form>
Table notesTable = new Table();
protected void Page_PreRender(object sender, EventArgs e)
{
Session["table"] = notesTable;
}
public void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
notesTable.ID = "MyTable";
}
else
{
notesTable = (Table)Session["table"];
TestPlaceHolder.Controls.Add(notesTable);
}
}
protected void TestAddNoteButton_Click(object sender, EventArgs e)
{
TableRow tr = new TableRow();
TableCell tc1 = new TableCell();
TableCell tc2 = new TableCell();
string strConn = db_connection_string_EINSTEIN;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT id, name FROM agl.guidelineNoteCategories";
con.Open();
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
dAdapter.Fill(objDs);
if (objDs.Tables[0].Rows.Count > 0)
{
System.Web.UI.WebControls.ListBox lb = new System.Web.UI.WebControls.ListBox();
System.Web.UI.WebControls.TextBox tb = new System.Web.UI.WebControls.TextBox();// { ID = sna.ToString()};
tb.Width = 1000;
tb.ID = "tb";
AjaxControlToolkit.AutoCompleteExtender ace = new AjaxControlToolkit.AutoCompleteExtender();
ace.ServiceMethod="searchNoteValues";
ace.MinimumPrefixLength=2;
ace.CompletionInterval=100;
ace.EnableCaching=false;
ace.CompletionSetCount=10;
ace.TargetControlID="tb";
ace.FirstRowSelected=false;
lb.BorderColor = System.Drawing.Color.Orange;
lb.DataSource = objDs.Tables[0];
lb.DataTextField = "name";
lb.DataValueField = "id";
lb.DataBind();
lb.Items.Insert(0, "--Select--");
tc1.Controls.Add(lb);
tc2.Controls.Add(tb);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
notesTable.Rows.Add(tr);
Session["table"] = notesTable;
ViewState["dynamictable"] = true;
}
con.Close();
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> searchNoteValues(string prefixText, int count)
{
string strConn = db_connection_string_EINSTEIN;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT id, NoteValue FROM agl.GuidelineNoteValues where isActive = 1 and NoteValue like '%' + #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
con.Open();
List<string> NoteValues = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
NoteValues.Add(sdr["NoteValue"].ToString());
}
}
con.Close();
return NoteValues;
}
}
Got it. Wasn't adding the auto complete extender to the form.
TestForm.Controls.Add(ace);

Attempting to get a count of records from gridview based on a selected date from dropdownlist but cant?

The problem lies that upon selection of the date in the dropdown it will give the count of the LAST selection, not the current.
I am a novice and the only thing I can think of is some type of postback issue? The gridview populates fine with the records selected by the DDL, so I just cant get my head around why the count that is rendered is the previous selection.
protected void ddlClassDate_SelectedIndexChanged(object sender, EventArgs e)
{
lblRecordCounter.Text = "";
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["gescdb"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT (*) FROM gescdb" +
"WHERE ClassDate=" + ddlClassDate.Text, conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
GridRegistrants.DataSource = reader;
GridRegistrants.DataBind();
reader.Close();
}
catch
{
}
finally
{
conn.Close();
lblRecordCounter.Text = GridRegistrants.Rows.Count.ToString();
}
In your Page_Load method you do the same, right? You have to move that code into following block:
if (!IsPostBack){
//Your code is here
}
Your DropDownList:
<asp:DropDownList ID="ddlClassDate" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlClassDate_SelectedIndexChanged" />
Your code behind:
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack){
BindDDL();
BindGrid(ddlClassDate.SelectedValue);
}
}
protected void BindDDL(){
//Bind Your dropdownlist here
}
protected void BindGrid(string ddate){
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["gescdb"].ConnectionString);
SqlCommand comm = new SqlCommand("select * from gescdb where ClassDate = #date", conn);
comm.Parameters.Add("#date", SqlDbType.VarChar).Value = ddate;
try
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
sda.Fill(ds);
GridRegistrants.DataSource = ds;
GridRegistrants.DataBind();
}
catch
{
//...
}
finally
{
conn.Close();
}
}
protected void ddlClassDate_SelectedIndexChanged(object sender, EventArgs e){
BindGrid(ddlClassDate.SelectedValue);
}

How to bind selected value from database in dropdownlist in asp.net

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

No output from search button

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 + "'%

Categories

Resources