I have a textbox and a label in ASP.NET and i want to automatically update the label with a value from database that is fetched using the content entered in textbox. This should be done dynamically when the text is changed in textbox and if a match if found in database, the corresponding value should be displayed in the label field (without page refresh). In this case I will enter employee ID in textbox and employee name should be displayed in label. I am using the following code,
<asp:ScriptManager ID="script_manager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="update_name" runat="server">
<ContentTemplate>
<asp:TextBox ID="text_empID" TextMode="Number" MaxLength="6" AutoPostBack="true" OnTextChanged="text_empID_TextChanged" runat="server"></asp:TextBox>
<asp:Label ID="label_empName" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
The code behind is as follows,
protected void text_empID_TextChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select EmployeeName from EmployeeTable where EmployeeID=#id", con);
cmd.Parameters.AddWithValue("#id", text_empID.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
label_empName.Text = dt.Rows[0]["EmployeeName"].ToString();
}
}
But this is not working. Also after entering a value in textbox and if i click outside the box, the text inside disappears. Is there any other way to do this? or am i doing something wrong here?
I would suggest that you should add a button because the text_changed event only fires when the text-box blurs (loses focus).
That's a very weird behaviour and most users are not used to it and will not expect it.
<ContentTemplate>
<asp:TextBox ID="text_empID" TextMode="Number" MaxLength="6" runat="server></asp:TextBox>
<asp:button id="btnSearch" runat="server" OnClick="text_empID_TextChanged" />
<asp:Label ID="label_empName" runat="server"></asp:Label>
</ContentTemplate>
In any case, have you added a breakpoint? does the event fire? do you get any data back in the DataTable?
EDIT
After your last comment I am convinced that you are clearing the contents of the label on page load.
please, make sure that you only do that in the following context:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
label_empName.Text = "";
}
}
Related
I can't get the dropdown onselectedindexchanged event to fire, and when I make a selection it resets the value of the dropdown onpostback, even though I have the if (!ispostback) in the page load event.
this is a content page in a master page in asp in case that matters.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:DropDownList ID="EventSVCProgList" runat="server"
EnableViewState="true"
OnSelectedIndexChanged="EventSVCProgList_SelectedIndexChanged"
AutoPostBack="true"></asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection constr = new SqlConnection(ConfigurationManager.ConnectionStrings["CBTestDBConnectionString"].ConnectionString);
SqlCommand eventsvcprogCMD = new SqlCommand("select*from SvcProg where eventatteligable=1", constr); // table name
SqlDataAdapter eventsvcadapt = new SqlDataAdapter(eventsvcprogCMD);
DataSet eventsvcset = new DataSet();
constr.Open();
eventsvcadapt.Fill(eventsvcset); // fill dataset
EventSVCProgList.DataTextField = eventsvcset.Tables[0].Columns["SvcProgID"].ToString(); // text field name of table dispalyed in dropdown
EventSVCProgList.DataValueField = eventsvcset.Tables[0].Columns["eventatteligable"].ToString();
EventSVCProgList.DataSource = eventsvcset.Tables[0]; //assigning datasource to the dropdownlist
EventSVCProgList.DataBind(); //binding dropdownlist
constr.Close();
}
}
protected void EventSVCProgList_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("Eat Poop");
var somevalue = EventSVCProgList.SelectedValue;
}
There are couple of things.
1) You need to add a Script Manager to the page at the top if not added already(it will give you a runtime error if you have not added a script Manager to the page)
2) You need to change the Update Panel content as shown below
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="EventSVCProgList" runat="server" AutoPostBack="True" OnSelectedIndexChanged="EventSVCProgList_SelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="EventSVCProgList" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
There seems that any parent control or page leven ViewState is disabled. please check in debug mode that what value you getting for EventSVCProgList.EnableViewState and other parent controls' as well.
thanks for the help. its still not working so i'm just going to try to use javascript instead. its got to be some fundamental flaw with the way the master page or content page is setup.
I have a repeater that I populate from a database:
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(#"SELECT CommunityName, CID, Budget FROM Donation WHERE Year = year(getdate()) ORDER BY CommunityName", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet);
myRep.ItemDataBound += new RepeaterItemEventHandler(myRep_ItemDataBound);
myRep.DataSource = myDataSet;
myRep.DataBind();
}
void myRep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var textbox = e.Item.FindControl("community");
textbox.ClientIDMode = ClientIDMode.Static;
textbox.ID = "community" + (e.Item.ItemIndex + 1);
}
Repeater:
<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:Repeater ID="myRep" runat="server">
<ItemTemplate>
<div class="form-group">
<asp:Label ID='thisLbl' runat="server" Text='<%# Eval("CommunityName") %>' />
<asp:TextBox runat="server" ID="community" Text='<%# Eval("Budget") %>' CssClass="form-control" />
</div>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
This creates 6 textboxes with labels and values, now my question is how do I detect which of these boxes belongs to the record it was initially pulled from in the database? I want to be able to modify the value in these boxes and hit a button to save them back to the database but I can't seem to wrap my head around getting them to the proper records.
Should I set the ID of the textbox to something I can parse through and match with the proper record? In the ItemDataBound?
You have to put a hidden field inside the repeater item template that takes the value from budget, and another hidden field to keep the CID value that has to be read in the post back request. Of course you need also a button and its click event handler.
<asp:Repeater ID="myRep" runat="server">
<ItemTemplate>
<div class="form-group">
<asp:Label ID='thisLbl' runat="server" Text='<%# Eval("CommunityName") %>' />
<asp:TextBox runat="server" ID="txtBudget" Text='<%# Eval("Budget") %>' CssClass="form-control" />
<asp:HiddenField runat="server" ID="hdOriginalBudget" Value='<%# Eval("Budget") %>' />
<asp:HiddenField runat="server" ID="hdCID" Value='<%# Eval("CID") %>' />
</div>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btn" runat="server" OnClick="btn_Click" />
In your code behind you need to loop inside the repeater to check whether the text box has been changed by comparing its value to the hidden field. After you save the budget value in the database you need to realign the hidden field value to the the new value entered by the user, otherwise you will always save that value after each post back:
protected void btn_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in myRep.Items)
{
var txtBudget = item.FindControl("txtBudget") as TextBox;
var hdOriginalBudget = item.FindControl("hdOriginalBudget") as HiddenField;
var hdCID = item.FindControl("hdCID") as HiddenField;
if (txtBudget.Text != hdOriginalBudget.Value)
{
//If you enter here means the user changed the value of the text box
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(#"UPDATE Donation SET Budget = #Budget WHERE CID = #CID", conn);
cmd.Parameters.Add(new SqlParameter("#Budget", int.Parse(txtBudget.Text)));
cmd.Parameters.Add(new SqlParameter("#CID", int.Parse(hdCID.Value)));
conn.Open();
cmd.ExecuteNonQuery();
}
//After you write in the database realign the values
hdOriginalBudget.Value = txtBudget.Text;
}
}
}
Take care that my code is missing the most basic validation, so if the user writes an invalid value in the textbox (for example "yyy") it breaks. So please don't put it in production as it is!
I have a button inside a listview and a label. The label is bound to my database and displays a score. If you press the button I want the score to update on client side. But Since I cant access items in Listview from codebehind I have no idea how to do this. And updatepanel does not work.
My listview bound to a Sqldatasource:
<asp:ListView ID="ListViewSearch" runat="server" DataSourceID="SqlDataSourceWebsite" DataKeyNames="WebsiteID">
My buttons and my label for rating:
<asp:LinkButton ID="BtnUp" runat="server" CssClass="btn btn-default btn-xs" CommandArgument='<%# Eval("testId").ToString() %>' OnClick="up_click"></asp:LinkButton>
<asp:LinkButton ID="BtnDown" runat="server" CssClass="btn btn-default btn-xs" CommandArgument='<%# Eval("testId").ToString() %>' OnCommand="down_click"></asp:LinkButton>
<asp:Label ID="LabelRating" runat="server" Text=' <%# Eval("rating") %>'></asp:Label>
upClick() function:
protected void up_click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
String webID = btn.CommandArgument.ToString();
int ID = Convert.ToInt32(webID);
click(ID, 1);
}
Click() function:
public void click(int webID, int vote)
{
using (SqlConnection con = new SqlConnection(strCon))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE [Test] SET [rating]+=#vote WHERE [testId]=#testID";
cmd.Parameters.AddWithValue("#webID", webID);
cmd.Parameters.AddWithValue("#vote", vote);
con.Open();
cmd.ExecuteNonQuery();
}
con.Close();
}
}
The code updates the rating as it is supposed to, but to see the change I have to refresh the page. So the questions is; How do I update a value inside a listview by clicking a button inside that same lisview?
(If this is not possible, please suggest a different way that I can display results from a search in a list that offers the same customization.)
I'm more into ASP MVC however maybe my tip will help you.
The way I did these behaviors was to bind javascript function to the button and using jQuery I've send 'GET' request to the specific action(method) on the server for example: www.myexample.com/getData?tableid=24 which responds with json containing needed data.
Hope this will direct you to proper solution.
Cheers,
Marek
Can anyone please help me i have in ASP.NET A Table called : info , with 3 columns : id,name,code
I want on a page called Default.aspx to have a checkboxlist that shows the table's Columns and when the user selects what columns he wants to see , then he presses a button to redirect him to Another Page and be shown in a Gridview (the gridview results to be show in a different page it's very important)
Page 1 :
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server" BackColor="#FFFFCC" Height="165px" Width="155px">
<asp:CheckBoxList ID="CheckBoxList1" runat="server"></asp:CheckBoxList>
<br />
</asp:Panel>
</div>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" style="height: 26px" Text="Button" />
<br />
</form>
Code behind Page 1 :
SqlConnection con = new SqlConnection("Server=.\\SQLEXPRESS;Database = ProiectWeb; Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
loadData();
}
}
private void loadData()
{
cmd.Connection = con;
cmd.CommandText = "SELECT column_name FROM information_schema.columns WHERE table_name ='info' ORDER BY ordinal_position";
con.Open();
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
CheckBoxList1.Items.Add(reader[0].ToString());
}
}
reader.Close();
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
}
Page 2 :
<asp:Panel ID="Panel2" runat="server" Height="302px" Width="278px">
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" style="margin-left: 0px">
</asp:GridView>
</asp:Panel>
Code Behind Page 2 :
SqlConnection con = new SqlConnection("Server=.\\SQLEXPRESS;Database = ProiectWeb; Integrated Security=True");
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
cmd.Connection = con;
loadGrid("SELECT * FROM info");
}
}
public void loadGrid(string query)
{
DataSet data = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(query,con);
adapter.Fill(data);
GridView1.DataSource = data;
GridView1.DataBind();
}
You need to follow, this.
In Button1_click event, get selected list of selected checkboxes and post them as query string to second page. I know querystring has length limitation and there are other way of passing values ( post data, session ..), but still if column list is less, you are good to go with this approach.
Following code will get list of selected columns, and redirect to second page.
protected void Button1_Click(object sender, EventArgs e)
{
List<string> selected = CheckBoxList1.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Text)
.ToList();
string sel = string.Join(",", selected);
Response.Redirect("Second.aspx?cols=" + sel);
}
In second page , page_load event read the querystring cols , and use Row_databound event of gridview to make rest of columns hidden except those passed in as querystring.
For this case, you can refer - GridView Hide Column by code OR Hide a GridView column by name at runtime in ASP.Net
Again, there are options to implement this, like generate dynamic SQL to get only required data and bind that to gridview. But the above seems simple one, that is why i explained in that way.
I have drop-down that is not showing the previoiusly selected value in my Detailview. It always shows me the first value in the list. If the previously selected value was xyz then when the Detailvies loads, i want to show xyz. I have researched a lot but could not find any solution that i can use. please help
here is my aspx code for the field that has the dropdown
<asp:TemplateField HeaderText="Name:">
<ItemTemplate>
<asp:Label ID="lbl_UID" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name") %>'></asp:Label></ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl_Name" Width="200px" Height="25" DataSourceID="SDS_Manager" DataTextField="FULL_NM" AutoPostBack="false"
DataValueField="UID" runat="server" AppendDataBoundItems="false">
<asp:ListItem Text="Select Name" Value="Select Name"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
here is the code behind that binds the detailview
protected void Edit(object sender, EventArgs e)
{
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
sqlcon.Open();
sqlcmd = new SqlCommand(#"Select PRJ_ID, WPC_CD, WPC_DESC, Name FROM myTable where PRJ_ID = '" + myvar + "' ", sqlcon);
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
sqlcon.Close();
DV_Edit.DataSource = dt;
DV_Edit.DataBind();
sqlcon.Close();
popup.Show();
}
}
Try setting AutoPostBack="true" and make sure if you have any logic to set the value of the drop down in the page load, that the code is not executed on post back as shown below.
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
ddlOne.DataSource = //your data here;
ddlOne.DataBind();
}
}
//if you don't wrap this logic in the if(!IsPostBack), the code will simply re-populate
//the drop down and set the selected index to the first item in the list with each
//post back.