How can I bind AutoCompleteExtender to dynamically created control? - c#

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

Related

How to display fixed data on textbox based on cascading dropdown list in C#?

I would like to know how can I display fixed data, based on the cascading dropdown list the user chooses? For example, I have 3 dropdown lists, on the last dropdown list if the user chooses "Yes", textbox will display "Position is approved" and if the user chooses "No", textbox will display "Position not approved". This is my code. I don't know what else to, please help.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillPackage();
}
}
private void FillPackage()
{
string strConn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT TopID, ToPackage FROM TableTop1";
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddl1.DataSource = objDs.Tables[0];
ddl1.DataTextField = "ToPackage";
ddl1.DataValueField = "TopID";
ddl1.DataBind();
ddl1.Items.Insert(0, "--Select--");
}
else
{
lblMsg.Text = "No Package found";
}
}
private void FillPurpose(int TopID)
{
string strConn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT PurposeID, Purpose FROM TablePurpose1 WHERE TopID =#TopID";
cmd.Parameters.AddWithValue("#TopID", TopID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddl2.DataSource = objDs.Tables[0];
ddl2.DataTextField = "Purpose";
ddl2.DataValueField = "PurposeID";
ddl2.DataBind();
ddl2.Items.Insert(0, "--Select--");
}
else
{
lblMsg.Text = "Please consult with focal person";
}
}
private void FillReason(int PurposeID)
{
string strConn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT ReasonID, Reason FROM TableReason1 WHERE PurposeID =#PurposeID";
cmd.Parameters.AddWithValue("#PurposeID", PurposeID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddl3.DataSource = objDs.Tables[0];
ddl3.DataTextField = "Reason";
ddl3.DataValueField = "ReasonID";
ddl3.DataBind();
ddl3.Items.Insert(0, "--Select--");
}
else
{
lblMsg.Text = "Please consult with focal person";
}
}
Since you have a Page_Load method in your snippet I'll consider your are using asp.net web forms. If that is the case you just have to handle the event emitted by the DropDownList component when it is changed.
I'm your c# code you should create a method to handle the event of an item being selected in your DropDownList, something like this:
protected void ItemSelected(object sender, EventArgs e)
{
if (ddl3.SelectedItem.Value == "Yes")
{
// Change text box text
}
}
And then you just have to hook your event handler to the component:
<asp:DropDownList ID="ddl3" runat="server" AutoPostBack="True"
onselectedindexchanged="ItemSelected">
</asp:DropDownList>

Cascading Dropdownlist not loaded on SelectedIndexChanged Event

I have two dropdownlists named ddFatherEmployeeNumber and ddEmployeeFatherName. Now on load event i am populating ddFatherEmployeeNumber from database. Here is the code
private DataTable LoadComboBoxFatherEmployeeNumber()
{
DataTable dtFatherENo = new DataTable();
using (SqlConnection con = new SqlConnection(Base.GetConnection))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id, EmployeeNo FROM TableFatherMaster", con))
{
cmd.CommandType = CommandType.Text;
con.Open();
SqlDataReader r = cmd.ExecuteReader();
dtFatherENo.Load(r);
}
}
return dtFatherENo;
}
Load Event code is
if (!IsPostBack)
{
ddFatherEmployeeNumber.DataSource = LoadComboBoxFatherEmployeeNumber();
ddFatherEmployeeNumber.DataTextField = "EmployeeNo";
ddFatherEmployeeNumber.DataValueField = "Id";
ddFatherEmployeeNumber.DataBind();
ddFatherEmployeeNumber.Items.Insert(0, new ListItem("Select Father Employee No", "0"));
}
Here is the .aspx code for ddFatherEmployeeNumber
<div class="col-8">
<asp:DropDownList ID="ddFatherEmployeeNumber" runat="server" class="form-control here" AutoPostBack="True" OnSelectedIndexChanged="ddFatherEmployeeNumber_SelectedIndexChanged"></asp:DropDownList>
</div>
Now i want to populate the ddEmployeeFatherName on the bases of ddFatherEmployeeNumber selected value. I mean when a user select employee number from ddFatherEmployeeNumber list then from database, Name of that employee loads and populate the ddEmployeeFatherName. For that purpose i already write a code on ddFatherEmployeeNumber_SelectedIndexChanged Event. Here is the Code.
protected void ddFatherEmployeeNumber_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddEmployeeFatherName.SelectedIndex == 0)
{
}
else
{
using (SqlConnection con = new SqlConnection(Base.GetConnection))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id, Name FROM TableFatherMaster WHERE EmployeeNo=#EmployeeNo ", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EmployeeNo", ddFatherEmployeeNumber.SelectedValue);
con.Open();
SqlDataReader r = cmd.ExecuteReader();
ddEmployeeFatherName.DataSource = r;
ddEmployeeFatherName.DataBind();
}
}
}
}
Now the problem is, it doesn't loads data into ddEmployeeFatherName.
Here is the picture for clear understanding
Try setting DataTextField and DataValueField properties for ddEmployeeFatherName first, because you're not setting them before using DataBind():
using (SqlConnection con = new SqlConnection(Base.GetConnection))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id, Name FROM TableFatherMaster WHERE EmployeeNo=#EmployeeNo ", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EmployeeNo", ddFatherEmployeeNumber.SelectedValue);
con.Open();
SqlDataReader r = cmd.ExecuteReader();
ddEmployeeFatherName.DataSource = r;
// set text and value fields
ddEmployeeFatherName.DataTextField = "Name";
ddEmployeeFatherName.DataValueField = "Id";
ddEmployeeFatherName.DataBind();
}
}
If the dropdownlist option values are still empty, try loading SqlDataReader contents into DataTable and use it instead:
using (SqlCommand cmd = new SqlCommand("SELECT Id, Name FROM TableFatherMaster WHERE EmployeeNo=#EmployeeNo ", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EmployeeNo", ddFatherEmployeeNumber.SelectedValue);
con.Open();
SqlDataReader r = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(r);
ddEmployeeFatherName.DataSource = dt;
ddEmployeeFatherName.DataTextField = "Name";
ddEmployeeFatherName.DataValueField = "Id";
ddEmployeeFatherName.DataBind();
}

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

Prevent duplicates when using LinkButton OnClick

How can I make it so when two people click on the LinkButton at the same time it allows one then prevents the other? I have this form where people are claiming records for themselves but the problem is people click the LinkButton nearly at the same time and then it proceeds to the next page for both of them and they both think the record is theirs.
ASP.NET
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Repeater ID="waitingRep" OnItemDataBound="waitingRep_ItemDataBound"
OnPreRender="waitingRep_PreRender" OnItemCommand="waitingRep_ItemCommand"
runat="server">
<ItemTemplate>
<asp:LinkButton ID="claimBtn" OnClick="claim" CommandArgument='<%# Eval("ID") %>' runat="server">
Claim
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind
protected void claim(object sender, EventArgs e)
{
var location = Request.Params["lid"];
string logon_user = Request.LogonUserIdentity.Name.Substring(7);
LinkButton claimButton = (LinkButton)(sender);
int currentID = Convert.ToInt32(claimButton.CommandArgument);
bool isTaken = false;
using (SqlConnection conn = new SqlConnection(""))
{
SqlCommand cmd = new SqlCommand(#"SELECT COUNT(*) as isTaken FROM ClaimList WHERE ID = '" + currentID + "' AND Status = 2", conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (Convert.ToInt32(rdr["isTaken"]) > 0) isTaken = true;
}
rdr.Close();
}
if (!isTaken)
{
using (SqlConnection conn = new SqlConnection(""))
{
SqlCommand cmd = new SqlCommand(#"UPDATE ClaimList set Status=#f1, ClaimedBy=#f2, ClaimedDate=#f3 where ID=#f4", conn);
conn.Open();
cmd.Parameters.Add("#f1", SqlDbType.Int).Value = 2;
cmd.Parameters.Add("#f2", SqlDbType.Int).Value = logon_user;
cmd.Parameters.Add("#f3", SqlDbType.DateTime).Value = DateTime.Now.ToString();
cmd.Parameters.Add("#f4", SqlDbType.Int).Value = currentID;
cmd.ExecuteNonQuery();
}
Response.Redirect("View.aspx?id=" + currentID);
}
else
{
Response.Redirect("Location.aspx?lid=" + location + "&action=taken");
}
}
Remove the select and add an extra condition to your update to avoid updating if it is already taken, like this:
bool isTaken = false;
using (SqlConnection conn = new SqlConnection(""))
{
SqlCommand cmd = new SqlCommand(#"UPDATE ClaimList set Status=#f1, ClaimedBy=#f2, ClaimedDate=#f3 where ID=#f4 AND Status <> 2", conn);
conn.Open();
cmd.Parameters.Add("#f1", SqlDbType.Int).Value = 2;
cmd.Parameters.Add("#f2", SqlDbType.Int).Value = logon_user;
cmd.Parameters.Add("#f3", SqlDbType.DateTime).Value = DateTime.Now.ToString();
cmd.Parameters.Add("#f4", SqlDbType.Int).Value = currentID;
if (cmd.ExecuteNonQuery() == 0)
isTaken = true;
}
if (!isTaken)
Response.Redirect("View.aspx?id=" + currentID);
else
Response.Redirect("Location.aspx?lid=" + location + "&action=taken");

Textboxes dont update when dropdownlist value is changed ASP.NET

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

Categories

Resources