Search bar by using LinQ - asp.net

I want to show the results only that match the user input, but this code will show the whole table, do you know what is the problem? For example, if the user enters "233442" id it will only show him the users that their id "233442". The user could search by id, name, or username.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace SearchBarLinQ
{
public partial class SearchBarLinQ : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
DataClasses1DataContext db = new DataClasses1DataContext();
protected void btnsearch_Click(object sender, EventArgs e)
{
var st = (from s in db.SearchTable2s where s.ID == int.Parse(TxtID.Text) select s).First();
TxtName.Text = st.Name;
TxtUsername.Text = st.Username;
LoadData();
}
void LoadData()
{
var st = from s in db.SearchTable2s select s;
GridView1.DataSource = st;
GridView1.DataBind();
}
}
}

Function btnsearch_Click is processing the search, but the value you found is not displayed. You need to assign the value found to the data source of girdview.
Refer to the sample code(Customize the param object of the LoadData function to be compatible with the view):
protected void btnsearch_Click(object sender, EventArgs e)
{
var st = (from s in db.SearchTable2s where s.ID == int.Parse(TxtID.Text) select s).First();
TxtName.Text = st.Name;
TxtUsername.Text = st.Username;
LoadData(st);
}
void LoadData(object param)
{
GridView1.DataSource = param;
GridView1.DataBind();
}

Related

How to Get DropDownList selected text and Fill details in GridView and labels based on that in asp.net

I have an ASP.NET site with a SQL Server 2008 database. I want to select the text of a dropdownlist and fill details in GridView and labels based on that, but when I select an item of selected text it does not fill details in GridView and labels.
Notice that my drop downlist is list of months. How can I fix this problem?
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class form : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["emp_dbConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ddlEmpRecord_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void BindEmpGrid()
{
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter();
try
{
SqlCommand cmd = new SqlCommand("select * from shakhes where mah_tadieh=" + ddlEmpRecord.Text + " ", con);
adp.SelectCommand = cmd;
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
grdEmp.DataSource = dt;
grdEmp.DataBind();
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
}
finally
{
dt.Clear();
dt.Dispose();
adp.Dispose();
}
}
protected void ddlEmpRecord_TextChanged(object sender, EventArgs e)
{
BindEmpGrid();
}
}
Use SelectedIndexChanged event instead of TextChanged event, and make sure your DropDownList AutoPostBack property is set to "true".
protected void ddlEmpRecord_SelectedIndexChanged(object sender, EventArgs e)
{
BindEmpGrid();
}
Hope it helps.

Extracting data from Table2 to TextArea of Table1

I have designed 2 tables in my aspx page. In table1 there is blank TextArea. In table2 there are fields like FirstName,LastName,Age,DOB and these attributes are already entered in the database. I have entered corresponding symbols for these attributes (for e.g. for Firstname symbol is {F}, for last name symbol is {L} etc..).
My requirement is when i click on a field of Table2 (for e.g. FirstName) it will be displayed on TextArea of table1 like "Hi My Name is {F}".
I have tried myself to do this program, but i did not extract the
symbol of the attribute in my textarea.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.UI.HtmlControls;
public partial class Default2 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=AITPLCP72\SQLEXPRESS;Initial Catalog=Template;Integrated Security=True");
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlDataAdapter adp = new SqlDataAdapter("select field,Symbols from temp2", con);
adp.Fill(ds);
}
}
protected void btnfirstname_onclick(object sender, EventArgs e)
{
Symbol("firstname");
}
protected void btnlastname_onclick(object sender, EventArgs e)
{
Symbol("lastname");
}
protected void btnage_onclick(object sender, EventArgs e)
{
Symbol("age");
}
protected void btndob_onclick(object sender, EventArgs e)
{
Symbol("dob");
}
protected void btnsubmit_Click1(object sender, EventArgs e)
{
string s = TextArea1.InnerHtml;
Response.Redirect("http://localhost:2482/Template1/Default3.aspx?text1=" + s);
}
public void Symbol(string s)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
if (row[0].ToString() == s.ToString())
{
string st = TextArea1.Value;
st += row["Symbols"];
TextArea1.Value = st;
}
}
}
}

how to import visual basic function into asp.net

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Microsoft.VisualBasic;
public partial class ReportGeneration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataSet query = (DataSet)Session["myDataset"];
GridView1.DataSource = query;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DateTime dt;
long age;
Datefunctions3.DateClass d1 = new Datefunctions3.DateClass();
//DateFunctions2.DateClass d1 = new DateFunctions2.DateClass();
if (e.Row.RowType == DataControlRowType.DataRow)
{
string s1 = e.Row.Cells[8].Text;
dt = Convert.ToDateTime(e.Row.Cells[8].Text);
// age = d1.DateDifference(da.Year, dt, DateTime.Now);
age = d1.DateDifference(DateInterval.year, d1, DateTime.Now);
e.Row.Cells[8].Text = age.ToString();
}
}
}
This is my code it shows error under the dateinterval not able to solve the problem have added a dll file of my visual basic function into the BIN folder as well
Here's an extension function that will give you the age w/o needing to use a VB function:
<Extension()> Function Age(dStart As DateTime) As Integer
Dim dNow As DateTime = DateTime.Now
Return dNow.Year - dStart.Year - If(dNow.Month > dStart.Month OrElse dNow.Month = dStart.Month AndAlso dNow.Day > dStart.Day,0,1)
End Function
usage:
age = d1.Age
or, if you don't want to use an extension, use it directly:
Dim dNow As DateTime = DateTime.Now
age = dNow.Year - d1.Year - If(dNow.Month > d1.Month OrElse dNow.Month = d1.Month AndAlso dNow.Day > d1.Day,0,1)
I just noticed that your code is C#... you'll need to convert my vb to C#

System.FormatException: Input string was not in a correct format

In the following code, when I try to add an Item to an ASP DropDownList, System.FormatException: Input string was not in a correct format, is thrown.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class ScheduleExam : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String connection = System.Configuration.ConfigurationManager.ConnectionStrings["TYCConnection"].ConnectionString;
String branch = Request.Form["ctl00$ctl00$MainContent$AdminMainContent$BranchDropDownList"];
if (!String.IsNullOrWhiteSpace(branch))
{
if (!branch.Equals("00"))
{
SqlConnection sqlConn = new SqlConnection(connection);
String semQuery = "select totalSem from branchTable where branchId='" + branch + "'";
SqlCommand semCommand = new SqlCommand(semQuery, sqlConn);
sqlConn.Open();
SqlDataReader semReader = semCommand.ExecuteReader();
semReader.Read();
int totalSem = Int32.Parse(semReader["totalSem"].ToString());
SemesterDropDownList.Items.Clear();
SemesterDropDownList.Enabled = true;
//ListItem list = new ListItem("Select");
SemesterDropDownList.Items.Add(new ListItem("select"));
for (int sem = 1; sem <= totalSem; sem++)
{
//SemesterDropDownList.Items.Add(sem.ToString());
}
sqlConn.Close();
}
else
{
SemesterDropDownList.Items.Clear();
SemesterDropDownList.Enabled = false;
//SemesterDropDownList.Items.Add("First Select Branch");
}
}
else
{
SemesterDropDownList.Enabled = false;
//SemesterDropDownList.Items.Add("First Select Branch");
}
}
protected void RegisterButton_Click(object sender, EventArgs e)
{
}
}
However, when I comment all such lines there is no exception thrown.
What could be the problem and its possible solution?
Instead of
int totalSem = Int32.Parse(semReader["totalSem"].ToString());
try
int totalSem;
Int32.TryParse(semReader["totalSem"].ToString(),totalSem);
and if that takes care of the exception then look into addressing the issues with that field.

Why The Gridview "AutoGenerateEditButton = true "property does not work in run time?

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class ExptGridviewEdit : System.Web.UI.Page
{
SqlCommand com;
SqlDataAdapter da;
DataTable dtb;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["gj"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
//if (!Page.IsPostBack)
//{
com = new SqlCommand("Select * from tblExpt", con);
da = new SqlDataAdapter(com);
dtb = new DataTable();
da.Fill(dtb);
if (dtb.Rows[0] != null)
{
BindData();
}
GridView1.AutoGenerateEditButton = true;
GridView1.RowUpdating += new GridViewUpdateEventHandler(GridView1_RowUpdating);
GridView1.DataKeyNames = new string[] { "id" };
GridView1.RowEditing += new GridViewEditEventHandler(GridView1_RowEditing);
// }
}
protected void BindData()
{
GridView1.DataSource = dtb;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataSource = dtb;
GridView1.DataBind();
}
}
When a data source control that supports updating is bound to a GridView control, the GridView control can take advantage of the data source control's capabilities and provide automatic updating functionality.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.autogenerateeditbutton.aspx

Resources