How to persist user control values? - c#

I want to persist user control values
If I add one more rows the previous control values is not there
I gone through some sites but I'm not able to understand clearly
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["ControlCount"] = ViewState["ControlCount"] == null ? 2 : ViewState["ControlCount"];
}
}
public int controlCount
{
get
{
int val = 0;
try
{
val = (int)ViewState["ControlCount"];
}
catch (Exception e)
{
// handle exception, if required.
}
return val;
}
set { ViewState["ControlCount"] = value; }
}
Here I am adding the User controls
protected void addnewtext_Click(object sender, EventArgs e)
{
int i = controlCount++;
for (int j = 0; j <= i; j++)
{
AddVisaControl ac = (AddVisaControl)Page.LoadControl("AddVisaControl.ascx");
Label lb = new Label();
string z = Convert.ToString(j + 1);
lb.Text = "Visa " + z;
rpt1.Controls.Add(lb);
lb.Attributes.Add("class", "style8");
rpt1.Controls.Add(ac);
rpt1.Controls.Add(new LiteralControl("<BR>"))
}
}
AddVisaUserControl.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="AddVisaControl.ascx.cs" EnableViewState="false" Inherits="Pyramid.AddVisaControl" %>
<div id="divreg" runat="server">
<table id="tbl" runat="server">
<tr>
<td>
<asp:Label ID="lbl2" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td> Visa Number:</td>
<td><asp:TextBox ID="txtUser" Width="160px" runat="server"/></td>
<td> Country Name:</td>
<td><asp:DropDownList ID="dropCountry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Type of Visa:</td>
<td><asp:DropDownList ID="dropVisa" Width="165px" runat="server"></asp:DropDownList></td>
<td> Type of Entry:</td>
<td><asp:DropDownList ID="dropEntry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Expiry Date</td>
<td>
</td>
</tr>
</table>
</div>

The dynamic controls must be added on every postback, so that ViewState can maintain its values. For more details, please read the ASP.NET page life cycle.

Related

ASP.NET passing a function return value from a modalpopupextender to the main form

I have looked at a number of solutions to my basic issue, but have not found any solution that I either understand or that would work.
I have a page that takes in two items of information, filename and a store. The user then clicks on a button to execute a function that will update a database and send back a resulting string that I want to display on a textbox on the main form.
However, when they press the button I call a modalpopupextender using an UpdatePanel panel. That gets a value into the modalpopup. If the user validates that the correct store is selected they click an 'okay' button which then call the dbprocessing function that returns a result. The page is small so I'll give the complete aspx and c# code.
The function doProcess() returns a List of values which I convert to String for display. I left the session variables in for that was my last attempt at trying to get this to work.
Where I am confused is that when the first button on the main form (Process) is clicked, there is a postback which obviously hits the page load before the button click. That is when I display the popup. Then when the user clicks on the button Okay, another postback is perform hitting page load before the button click and in that second button I originally tried to set the textbox on the main page because there is no other action after the second click, but no data displayed.
What is strange, if I repeat the process, when I click to display the popup, my data displays. This is not making sense.
This is the aspx page
<%# Page Title="Product Rank Loader" Language="C#" MasterPageFile="~/OMnested.master" AutoEventWireup="true" CodeBehind="ProductRankLoader.aspx.cs" Inherits="OrderManager.ProductRankLoader" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="Scripts/local.js"></script>
<script type="text/javascript">
function callme(thisone)
{
$("#ddlStores").prop('disabled', false);
}
</script>
<div>
<table style="width: 500px">
<tr>
<td>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:FileUpload ID="fulRanks" runat="server" Width="315px" />
</td>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddlStores" runat="server" Height="16px" Width="155px">
<asp:ListItem Value="0">Select Store</asp:ListItem>
<asp:ListItem Value="10101">Parkseed</asp:ListItem>
<asp:ListItem Value="10151">Wayside</asp:ListItem>
<asp:ListItem Value="10201">Jackson (JP)</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td style="height: 20px; padding-top: 15px; padding-bottom: 15px; padding-left: 20px;">
<asp:Button ID="btnProcess" runat="server" Text="Process" Width="89px" OnClick="btnProcess_Click" />
</td>
</tr>
<tr>
<td>
**<asp:TextBox ID="txtResults" runat="server" Height="200px" ReadOnly="True" TextMode="MultiLine"></asp:TextBox>**
</td>
</tr>
</table>
<asp:HiddenField ID="hdnFilename" runat="server" />
</div>
<asp:UpdatePanel id="updVerifyChoice" runat="server">
<ContentTemplate>
<div style="display: none;">
<asp:Button ID="btnDummy" UseSubmitBehavior="true" OnClientClick="ShowModalPopup" OnClick="btnDummy_Click" runat="server" />
<%--Dummy Button added to assign the target controlid of PopupExtender--%>
<asp:Button ID="btnDummyButton" UseSubmitBehavior="true" runat="server" Text="DummyButton" Style="display: none;" />
</div>
<asp:Panel ID="pnlVerifyRequestPopup" runat="server">
<div style="background: #fff; padding-left: 3px; border: 1px solid #989898; border-top: 1px solid #989898 !important;">
<table style="background-color: #F7F5F4; width: 300px;">
<tr>
<td><label>Verify Process Request</label></td>
<td style="text-align: right;">
<label class="lbl_3">
<asp:LinkButton ID="lBtnVerifyRequestClose" CssClass="lnkCloseheaderedit" Text="Cancel"
runat="server" OnClick="lBtnBillUpdPopClose_Click" /></label>
</td>
</tr>
<tr>
<td style="width: 150px;" colspan="2">
<asp:Label ID="lblWarn" runat="server" Text="" Font-Size="Medium" ForeColor="#CC3300"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2" class="align_right">
<asp:Button ID="btnPopVerify" runat="server" CssClass="order_searchbtn" Text="Okay"
OnClick="btnPopVerify_Click" />
</td>
</tr>
</table>
<asp:HiddenField ID="hdnReturnData" runat="server" />
</div>
</asp:Panel>
<ajax:ModalPopupExtender ID="extVerifyProcess" runat="server" BehaviorID="extndPopBillUpdBehId"
TargetControlID="btnDummyButton" PopupControlID="pnlVerifyRequestPopup" CancelControlID="lBtnVerifyRequestClose">
</ajax:ModalPopupExtender>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
The field in question that should get the returned values from the function is called txtResults.
Here is the c# code (I cut out unneeded code)
namespace OrderManager
{
public partial class ProductRankLoader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var currentUser = Request.LogonUserIdentity.Name.Split('\\')[1];
// Session.Add("returnText", "");
var header = Master.FindControl("lblpageheading") as Label;
header.Text = "Product Rank Loader";
if (IsPostBack)
{
try
{
//if (Session["Verified"].ToString() != "")
//{
Session["returnText"] = doProcess();
if (Session["returnText"].ToString() != "")
{
txtResults.Text = Session["returnText"].ToString();
lblMessage.Text = "";
}
//}
}
catch { }
} else
{
Session.Add("returnText", "");
Session.Add("Verified", "");
}
}
protected void btnProcess_Click(object sender, EventArgs e)
{
Boolean fileOK = false;
string filename = Path.GetFileName(fulRanks.FileName);
hdnFilename.Value = filename;
if (fulRanks.HasFile)
{
ddlStores.Enabled = true;
String fileExtension =
System.IO.Path.GetExtension(fulRanks.FileName).ToLower();
String[] allowedExtensions = { ".txt", ".log" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
fulRanks.SaveAs(#"c:\temp\" + filename);
}
}
}
if (!fileOK || ddlStores.SelectedIndex <= 0)
{
lblMessage.Text = "Either the file name is incorrect or a store has not been selected.";
return;
} else { }
lblWarn.Text = "You are going to update item Ranks for store <br />" + ddlStores.SelectedItem + ".<br /><br />Press 'Okay' to process";
Session.Add("Verified", "true");
extVerifyProcess.Show();
}
protected void lBtnBillUpdPopClose_Click(object sender, EventArgs e)
{
Session["Verified"] = "";
Session["returnText"] = "";
Response.Redirect("ProductRankLoader.aspx");
}
protected void btnPopVerify_Click(object sender, EventArgs e)
{
//Session["returnText"] = doProcess();
Session.Remove("returnText");
Session.Remove("Verified");
}
private string doProcess()
{
string tmpResults = "";
Int32 store = 0;
if (ddlStores.SelectedIndex > 0)
{
Int32.TryParse(ddlStores.SelectedValue.ToString(), out store);
string filename = hdnFilename.Value;
ProductRankLoaderDLL.ProductRankLoaderDLL newRanks = new ProductRankLoaderDLL.ProductRankLoaderDLL(xxx);
List<string> results = newRanks.ProcessRanks();
foreach (string result in results)
{
tmpResults += result + '\r';
}
// txtResults.Text = tmpResults;
lblMessage.Text = "";
}
else
{
lblMessage.Text = "";
}
return tmpResults;
}
protected void btnDummy_Click(object sender, EventArgs e)
{
}
}
}
If I don't misunderstand your request your problem is caused by the postbacks. I think you can handle better your logic with jquery. For example you can use jquery to close the popup without performing postback:
$('#lBtnVerifyRequestClose').click(function (event) {
event.preventDefault();
$('#pnlVerifyRequestPopup').dialog('close');
});
the event.preventDefault() ensure that postback are not executed.
If you need server logic to put data on your popup you can bind a jquery function to the dialog on open event and retrieve there data / perform your logic. In this way your form will be submitted to the server only once at the end of the process.

Dropdownlist resetting and not keeping value during postbacks

I know this is a quite common problem but I couldn't find a solution over internet yet. Maybe I got into a tunnel vision, I don't know.
I have a gridview and the dropdownlist related to it keeps resetting. It's been hours and I'm still having this problem.
The table which has the DropDownList
<table class="filtertable" EnableViewState="true">
<tr align="center">
<td width="100%">
<asp:Button ID="btnNew" runat="server" Text="Yeni Kayıt" OnClick="btnNew_OnClick"
CssClass="btn" Visible="true" />
<asp:Button ID="btnArama" runat="server" Text="Gümrük Arama" OnClick="btnArama_Click"
CssClass="btn" Visible="false" />
</td>
</tr>
<tr runat="server" id="trGumrukArama">
<td>
<fieldset style="margin-top: 5px">
<legend>Ülke Gümrük Arama</legend>
<table EnableViewState="true">
<tr>
<td>
<asp:Label runat="server" ID="lblUlke">Ülke:&nbsp</asp:Label>
</td>
<td>
<asp:DropDownList runat="server" ID="drpUlke" AppendDataBoundItems="true" EnableViewState="true"
OnSelectedIndexChanged="drpUlke_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td>
<asp:Label runat="server" ID="lblGumrukKodu"> Gümrük Kodu: &nbsp</asp:Label>
</td>
<td>
<asp:TextBox runat="server" ID="txtGumrukKodu"></asp:TextBox>
</td>
<td>
<asp:Label runat="server" ID="lblGumrukAdi">Gümrük Adı: &nbsp</asp:Label>
</td>
<td>
<asp:TextBox runat="server" ID="txtGumrukAdi"></asp:TextBox>
</td>
<td>
<asp:Button runat="server" CssClass="btn" ID="btnSearch" Text="Ara" OnClick="btnSearch_OnClick" />
</td>
</tr>
</table>
</fieldset>
</td>
</tr>
</table>
CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
drpUlke_Bind();
BindList();
//drpUlke.SelectedValue = ViewState["ListUlkeKod"].ToString();
}
}
protected void drpUlke_Bind()
{
DataTable dt = CacheManager.UlkelerGercek.Tables[0];
DataTable dtNew = CacheManager.UlkelerGercek.Tables[0].Clone();
DataRow drseperator = dtNew.NewRow();
drseperator["id"] = -1;
drseperator["harfKod"] = "";
drseperator["adi"] = "------------------------------------";
dtNew.Rows.Add(drseperator);
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dtNew.NewRow();
dr.ItemArray = dt.Rows[i].ItemArray;
dr["adi"] = dr["harfKod"] + " - " + dr["adi"];
if (dr["harfKod"].ToString().Trim() == "TR")
dtNew.Rows.InsertAt(dr, 0);
else
dtNew.Rows.Add(dr);
}
drpUlke.DataSource = dtNew;
drpUlke.DataValueField = "harfKod";
drpUlke.DataTextField = "adi";
drpUlke.DataBind();
drpKaydetUlke.DataSource = dtNew;
drpKaydetUlke.DataValueField = "harfKod";
drpKaydetUlke.DataTextField = "adi";
drpKaydetUlke.DataBind();
}
protected void drpUlke_SelectedIndexChanged(object sender, EventArgs e)
{
}
.
.
.
.
.
private void BindList()
{
int TotalCount;
int Start = (CurrentPageIndex - 1) * _pageRowCount;
string UlkeKodu = drpUlke.SelectedValue;
//ViewState["ListUlkeKod"] = UlkeKodu;
string GumrukKodu = txtGumrukKodu.Text;
string GumrukAdi = txtGumrukAdi.Text;
//drpUlke.SelectedValue = ViewState["ListUlkeKod"].ToString();
DataSet ds = (Stored Procedure Here)
gvUlkeGumruk.DataSource = ds;
gvUlkeGumruk.DataBind();
int intTotalCount;
int intCurrentCount;
intTotalCount = TotalCount == -1 ? 0 : TotalCount;
intCurrentCount = ds.Tables[0].Rows.Count - 1;
pcBottom.TotalRowCount = intTotalCount;
pcBottom.PageRowCount = _pageRowCount;
pcBottom.CurrentRowCount = intCurrentCount;
pcBottom.BindPaging();
pcBottom.Visible = intTotalCount > 0;
}
Just the related parts, If I'm missing something please let me know.
I tried using viewstate variables but they kept getting resetted too.
edit:
I came across a few posts on internet about this problem. They were saying as a solution that their dropdown lists value field not being unique. I checked the value field and it's values are all unique.
When you want the DDL data to survive a postback you've got to reload the DDL during the postback lifecycle. You can do this manually, or enable ViewState which you'd have to do on the control chain.
If you go the manual route of loading data in control/page init (regardless of the IsPostBack flag) you can improve performance by making sure your data is cached. You'll be skipping the ViewState (good for client performance), but hitting your DB more. If that's a problem then you can go back to using ViewState.
This may happens because of AppendDataBoundItems="true". Removed that property and try again
The answers above are true on their own cases and not to be dismissed as incorrect. Due to the nature of my problem, I can't designate one as answer.
I ended up sending drop down choice as a request parameter to each other page. We are using a custom pagination mechanism and that is the reason I had to end up this way.

C# asp.net chart control, Get the pie slice color of data points

I have an control, with a Pie Series. Is there a way to retrieve the Pie Slice Color of each Data Point in the DataBound event of the Series? Any suggestion is appreciated.
The reason I need that is that I need to show a whole lot of other data for each Data Point. I don't want to put that in the legend as, it takes too much of space and there could be lot of other data to be displayed in the future.
<asp:Chart ID="TRsClosedByDevelopers" runat="server" Height="892px"
BorderlineDashStyle="Solid" BorderlineWidth="2" BorderSkin-SkinStyle="Emboss"
BorderlineColor="BlueViolet" Width="980px" Palette="Pastel"
style="margin-left:-8px; margin-top:-8px;" EnableViewState="True"
SuppressExceptions="True" ondatabound="TRsClosedByDevelopers_DataBound">
<Titles>
<asp:Title BackColor="LightSteelBlue" BackGradientStyle="VerticalCenter"
BorderColor="SteelBlue" BorderWidth="0"
Font="Microsoft Sans Serif, 15.75pt, style=Bold" ForeColor="DarkSlateGray"
IsDockedInsideChartArea="False" Name="PieChartTitle"
Text="TR's Closed in the past ">
</asp:Title>
</Titles>
<Series>
<asp:Series Name="Testing1"
Font="Microsoft Sans Serif, 9.75pt, style=Bold" BorderColor="0, 0, 192"
ChartType="Pie" LabelForeColor="DarkSlateGray"
CustomProperties="MinimumRelativePieSize=50, CollectedSliceExploded=True, CollectedLegendText=OTHER, CollectedColor=ActiveBorder, CollectedLabel=OTHER (#VALY) (#PERCENT{P2}), PieLabelStyle=Outside, CollectedThreshold=1"
YValueType="Int32" Label="#VALX"
XValueType="String">
<SmartLabelStyle CalloutLineAnchorCapStyle="Diamond"
AllowOutsidePlotArea="Yes" />
<EmptyPointStyle IsValueShownAsLabel="false" IsVisibleInLegend="false"
BorderWidth="0" CustomProperties="PieLabelStyle=Disabled" MarkerBorderWidth="0"
MarkerSize="0" />
</asp:Series>
</Series>
<ChartAreas>
<asp:ChartArea Name="ChartArea2">
<Area3DStyle Enable3D="true" Inclination="0" />
</asp:ChartArea>
</ChartAreas>
<BorderSkin SkinStyle="Emboss" />
</asp:Chart>
</td>
<td>
<table cellspacing="2" cellpadding="2" style="width:100%; margin-left:-2px;">
<tr style="background-color:#cccccc; font-size:large;">
<th style="width:30px;">
</th>
<th align="left" style="width:260px;">
Developer
</th>
<th>
TR's Closed
</th>
</tr>
</table>
<asp:Repeater ID="TRsClosedTbl" runat="server" OnItemDataBound="TRsClosedTbl_ItemDataBound">
<HeaderTemplate>
<table cellspacing="2" cellpadding="2" style="width:100%; margin-left:-2px;" id="SummaryTbl">
</HeaderTemplate>
<ItemTemplate>
<tr style="background-color:#eeeeee; height:24px; font-size:large;" class="normalCell">
<td style="width:30px;" runat="server" id="ColorCell"> </td>
<td style="width:260px;"><%#((DataRowView)Container.DataItem)["Developer"]%></td>
<td align="right" style="width:50px"><%#((DataRowView)Container.DataItem)["TRsClosed"]%></td>
<td align="right"><%#String.Format("{0:N2}", Math.Round(Convert.ToDouble(((DataRowView)Container.DataItem)["TRsClosed"])/Convert.ToDouble(srv_nTotalTRsClosed) * 100, 2))%> %</td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr style="background-color:#eeeeff; height:24px; font-size:large;" class="normalCell">
<td style="width:30px;" runat="server" id="ColorCell"> </td>
<td style="width:260px;"><%#((DataRowView)Container.DataItem)["Developer"]%></td>
<td align="right" style="width:50px"><%#((DataRowView)Container.DataItem)["TRsClosed"]%></td>
<td align="right"><%#String.Format("{0:N2}", Math.Round(Convert.ToDouble(((DataRowView)Container.DataItem)["TRsClosed"])/Convert.ToDouble(srv_nTotalTRsClosed) * 100, 2))%> %</td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
<tr style="background-color:#EEFFCC; height:24px; font-size:large;" class="normalCell">
<td align="right" colspan="2">TOTAL:</td>
<td align="right"><%=srv_nTotalTRsClosed%></td>
<td> </td>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
</td>
</tr>
</table>
The code behind file is:
public partial class ER_RecentTRsClosedPieChart : System.Web.UI.Page
{
public DataAccessLayer DAL;
public DataSet srv_TRsClosedByDevDS;
public string srv_sToday;
public int srv_nNumDays = 0;
public int srv_nTotalTRsClosed = 0;
private int index = 0;
protected void Page_Load(object sender, EventArgs e)
{
DAL = new DataAccessLayer();
srv_TRsClosedByDevDS = new DataSet();
srv_sToday = "09/14/2012";//DateTime.Now.ToString("MM/dd/yyyy");
if (!int.TryParse(Request.QueryString["NumDays"], out srv_nNumDays))
srv_nNumDays = 7;
srv_TRsClosedByDevDS = DAL.CRM_RequestMQEx(srv_nNumDays, 0, 0, 0, 0, srv_sToday, "", "", "", "", 13);
srv_nTotalTRsClosed = SumColumn(srv_TRsClosedByDevDS.Tables[0], "TRsClosed");
TRsClosedByDevelopers.Titles[0].Text += srv_nNumDays.ToString() + " Days (TOTAL: " + srv_nTotalTRsClosed.ToString() + ")";
TRsClosedByDevelopers.Series["Testing1"].Points.DataBind(srv_TRsClosedByDevDS.Tables[0].AsEnumerable(), "Developer", "TRsClosed", string.Empty);
srv_TRsClosedByDevDS.Tables[0].Columns.Add("PieColor");
TRsClosedTbl.DataSource = srv_TRsClosedByDevDS.Tables[0];
TRsClosedTbl.DataBind();
}
public int SumColumn(DataTable dt, string columnName)
{
return (from c in dt.AsEnumerable()
where !c.IsNull(columnName)
select c.Field<int>(columnName)
).Sum();
}
protected void TRsClosedTbl_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
}
protected void TRsClosedByDevelopers_DataBound(object sender, EventArgs e)
{
string r;
string g;
string b;
for (int i = 0; i < TRsClosedByDevelopers.Series["Testing1"].Points.Count; i++)
{
string dev = TRsClosedByDevelopers.Series["Testing1"].Points[i].Color.ToString();
//Here, I Want to add the rendered Pie Slice color to the DataColumn "PieColor" of each row.
//r = TRsClosedByDevelopers.Series["Testing1"].Points[i].MarkerColor.R.ToString();
//g = TRsClosedByDevelopers.Series["Testing1"].Points[i].MarkerColor.G.ToString();
//b = TRsClosedByDevelopers.Series["Testing1"].Points[i].MarkerColor.B.ToString();
}
}
}
Have you tried to set a custom palette for your chart?
chart.Palette = ChartColorPalette.None;
Colors[] myColors = {Color.Red, Color.Green, Color.Blue, ...};
chart.PaletteCustomColors = myColors;
You could now use the color array for future operations. the color of the first slice is myColors[0] etc.

Retrieving value from Asp.Net TextBox

Problem: I have an asp.net Textbox that I am putting text into and on text change it should assign its value to a variable, this does not happens.
Question: What is the best method to retrieve the value from the Textbox?
C# Code:
protected void btnSourceConnect_Click(object sender, EventArgs e)
{
if (Util.Connection(SourceString, 0))
{
lblTesting.Text = "Working!";
}
else
{
lblTesting.Text = "It No Work";
}
}
protected void txtSourceServer_TextChanged(object sender, EventArgs e)
{
SourceString.DataSource = txtSourceServer.Text;
}
protected void txtSourceDatabase_TextChanged(object sender, EventArgs e)
{
SourceString.InitialCatalog = txtSourceDatabase.Text;
}
protected void txtSourceUN_TextChanged(object sender, EventArgs e)
{
SourceString.UserID = txtSourceUN.Text;
}
protected void txtSourcePass_TextChanged(object sender, EventArgs e)
{
SourceString.Password = txtSourcePass.Text;
}
Asp.Net Code:
<table style="width: 100%;Border:1px solid Black;">
<tr>
<td class="style1">
Source Server:</td>
<td class="style1">
<asp:TextBox ID="txtSourceServer" runat="server"
ontextchanged="txtSourceServer_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
<td class="style1">
Source Database:
</td>
<td class="style1">
<asp:TextBox ID="txtSourceDatabase" runat="server"
ontextchanged="txtSourceDatabase_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
User Name:
</td>
<td class="style1">
<asp:TextBox ID="txtSourceUN" runat="server"
ontextchanged="txtSourceUN_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
<td class="style1">
Password:
</td>
<td class="style1">
<asp:TextBox ID="txtSourcePass" runat="server"
ontextchanged="txtSourcePass_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
</td>
<td class="style1">
</td>
<td class="style1">
</td>
<td class="style1">
<asp:Button ID="btnSourceConnect" runat="server" Text="Test Connection"
onclick="btnSourceConnect_Click" />
</td>
</tr>
</table>
What is the best method to retrieve the value from the Textbox?
The best method is like this control I am writing right now, you have a button that make post back, and then you read the value of the text box on code behind - on post back.
Using the AutoPostBack="True" on every TextBox you use involves too many unnecessary post backs to the server, it is better to use a "submit" button and save all your values when the user click on submit.
In you case you have a button, and you only need to remove the auto post back and set your values only when you try to connect as:
protected void btnSourceConnect_Click(object sender, EventArgs e)
{
SourceString.UserID = txtSourceUN.Text;
SourceString.DataSource = txtSourceServer.Text;
SourceString.InitialCatalog = txtSourceDatabase.Text;
SourceString.Password = txtSourcePass.Text;
if (Util.Connection(SourceString, 0))
{
lblTesting.Text = "Working!";
}
else
{
lblTesting.Text = "It No Work";
}
}
AutoPostback = true on a TextBox will cause the page to post back when the text box loses focus, not on every text change.
From the look of your code most of this functionality should be happening on the client side (i.e. with javascript).

Fill dropdown list in casceding way and set each dropdown list before its first value

In my project I am making one form which contains three dropdown lists each for company,department and vacancies with "Select" as their default text. I am feeling company dropdown list at form load event but default text is "Select" now when user select company, second list should be filled with departments of selected company but default text should be "select". Again when user select department,the third list should be filled with vacancies on the selected department of selected company but default text should be "select".
I am trying to fill other two dropdown list with "selected index change" event of company list and department list respectively. but its not working as I want.
Here is my code for .aspx page.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<table width="100%">
<tr>
<td colspan="4">
</td>
</tr>
<tr>
<td align="center" class="tdtitle" colspan="4">
Search Candidates
</td>
</tr>
<tr>
<td colspan="4">
</td>
</tr>
<tr>
<td class="RowHeight" width="20%">
Select Company</td>
<td width="30%">
<asp:DropDownList ID="companyList" runat="server" AutoPostBack="True"
onselectedindexchanged="companyList_SelectedIndexChanged" Width="150px">
<asp:ListItem>-Select Company-</asp:ListItem></asp:DropDownList>
</td>
<td width="20%">
Select Department</td>
<td width="30%">
<asp:DropDownList ID="deptList" runat="server" AutoPostBack="True"
Width="150px" onselectedindexchanged="deptList_SelectedIndexChanged" onclick="Validate();">
<asp:ListItem>-Select Department-</asp:ListItem></asp:DropDownList>
</td>
</tr>
<tr>
<td class="RowHeight" width="20%">
Select Vacancy</td>
<td colspan="3" width="*">
<asp:DropDownList ID="vacanyList" runat="server" Width="200px">
<asp:ListItem>-Select Vacancy-</asp:ListItem></asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="4">
</td>
</tr>
<tr>
<td colspan="4">
</td>
</tr>
<tr>
<td colspan="4">
</td>
</tr>
<tr>
<td colspan="4">
</td>
</tr>
<tr>
<td align="center" colspan="4">
<asp:Label ID="notifyLbl" runat="server" Font-Size="Large" ForeColor="Red"
Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td colspan="4">
</td>
</tr>
</table>
<script type="text/javascript">
function alertOnBadSelection() {
var select = document.getElementById('companyList');
if (select.options[select.selectedIndex].value == "-Select Company-") {
alert('Please Select Company!');
return false;
}
}
</script>
</asp:Content>
/And below is the code for my .aspx.cs page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class HR_Department_searcAppForVac : System.Web.UI.Page
{
DataOperation oDo = new DataOperation();
protected void Page_Load(object sender, EventArgs e)
{
// deptList.Attributes.Add("onchange", "alertOnBadSelection();");
notifyLbl.Visible = false;
if (!IsPostBack)
{
try
{
DataTable objCmpnyTable = oDo.DropDownList("select * from tblCompanyMaster");
if (objCmpnyTable.Rows.Count > 0)
{
foreach (DataRow Row in objCmpnyTable.Rows)
{
companyList.Items.Add(new ListItem(Row["CompName"].ToString(), Row["CompId"].ToString()));
}
}
else
{
notifyLbl.Visible = true;
notifyLbl.Text = "There is not any company in the list.";
}
}
catch (Exception)
{
throw;
}
}
else
{
//deptList.SelectedIndex = -1;
//vacanyList.SelectedIndex = 1;
}
}
protected void companyList_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (companyList.SelectedIndex > 0)
{
deptList.Items.Clear();
string str = "select * from vwCompWiseList where CompId=" + companyList.SelectedValue;
DataTable objDeptTable = oDo.DropDownList("select DeptId,DeptName from vwCompWiseDept where CompId= "+companyList.SelectedValue);
if (objDeptTable.Rows.Count > 0)
{
foreach (DataRow Row in objDeptTable.Rows)
{
deptList.Items.Add(new ListItem(Row["DeptName"].ToString(), Row["DeptId"].ToString()));
}
}
}
else
{
notifyLbl.Visible = true;
notifyLbl.Text = "Select Company....";
}
}
catch (Exception)
{
throw;
}
}
protected void deptList_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (deptList.SelectedIndex > 0)
{
vacanyList.Items.Clear();
DataTable objVacancytbl = oDo.DropDownList("select VacId,VacTitle from tblVacancyMaster where DeptId =" + deptList.SelectedValue + " and CompId=" + companyList.SelectedValue);
if (objVacancytbl.Rows.Count > 0)
{
foreach (DataRow Row in objVacancytbl.Rows)
{
vacanyList.Items.Add(new ListItem(Row["VacTitle"].ToString(), Row["VacId"].ToString()));
}
vacanyList.SelectedIndex = -1;
vacanyList.ClearSelection();
}
else
{
notifyLbl.Visible = true;
notifyLbl.Text = "Ops..!There is no available vacancy....";
}
}
else
{
notifyLbl.Visible = true;
notifyLbl.Text = "Select Department...";
}
}
catch (Exception)
{
throw;
}
}
}
Please show my problem and its solutions.
I think you may want to leverage jquery cascading drop downs . Using a cascading drop down javascript (jquery) will call back and reload dependent drop downs based on the value(s) selected in the previous drop down.

Categories