Show dropdown selected value in the grid on the same page - c#

I have a drop down which has the list of delegates. When the user selects a delegate then I populate the available meet-timings in the second dropdown using the selectedindexchange event of the 1st dropdown
Aspx page
<asp:DropDownList ID="delegate_ddl" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddldelegates_SelectedIndexChanged" Width="200px"></asp:DropDownList>
<asp:DropDownList ID="delegatetime_ddl" runat="server" Width="90px"></asp:DropDownList>
<asp:Button ID="adddelegate" runat="server" Text="Add" onclick="adddelegate_Click"/>
.cs page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds1 = getdata.getdelegatelist();
delegate_ddl.DataSource = ds1.Tables[0];
delegate_ddl.DataTextField = "DELEGATE_NAME";
delegate_ddl.DataValueField = "DELEGATE_ID";
delegate_ddl.DataBind();
delegate_ddl.Items.Insert(0, "--Select--");
}
}
protected void ddldelegates_SelectedIndexChanged(object sender, EventArgs e)
{
string delselection = delegate_ddl.SelectedValue.ToString();
DataSet ds2 = getdata.getdelegatetimelist(delselection);
if (ds2.Tables[0].Rows.Count > 0)
{
delegatetime_ddl.DataSource = ds2.Tables[0];
delegatetime_ddl.DataTextField = "TIMESLOT";
delegatetime_ddl.DataValueField = "TIMEID";
delegatetime_ddl.DataBind();
}
else
{
time_lbl.Text = "No slots Open";
}
}
protected void adddelegate_Click(object sender, EventArgs e)
{
string delegateselected = delegate_ddl.SelectedValue.ToString();
string timeslotselected = delegatetime_ddl.SelectedValue.ToString();
getdata.delegatemeetinsert(personidd, delegateselected, timeslotselected);
}
Now the data gets inserted – but my question here is
As soon as the user click add button I would like to display the delegate selected and the time slot selected in a some sort of a grid view or dynamic table below with a delete option.
Can someone please provide a code sample in C# to achieve the above

Instead of using Gridview for displaying data use some basic control like Labels,it will reduce lot's of unncessary code. use Asp.net 'Panel' control and encapsulate all label and button(for delete purpose) into Panel then hide/show according to need. here is the outline of code that might help you,
if(!page.IsPostBack) // This goes into Page_Load
{
Panel1.Visible=false;
}
protected void adddelegate_Click(object sender, EventArgs e) // add this additional code
{
Panel.Visible=True;
GetDelegate()// This method retrieve the delegate you inserted..
Lable1.Text= "Set here Delegate name you just Retrieved"
Label2.Text="Delegate time you retrived"
}
protected void BtnRemovedelegate_Click(object sender, EventArgs e)
{
string Personidd= retrieve person id
string delegateName= Lable1.text;
String timeslot=Label2.Text
SomeDeleteMethod(personidd, delegateName, timeslot);
Panel1.Visible=false;
}
Hope you get the idea..

Related

How to save option selected in Dropdownlist after selection

I am displaying columns in a GridView and one of the columns is a dropdownlist. I want to be able to save the option selected in the dropdownlist as soon as something is selected. I have done this with one of the columns that has a textbox so I was hoping to do something similar with the DropDownList.
The code for the textbox and dropdownlist:
protected void gvPieceDetails_ItemDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
JobPieceSerialNo SerNo = e.Row.DataItem as JobPieceSerialNo;
if (SerNo != null) {
TextBox txtComment = e.Row.FindControl("txtComment") as TextBox;
txtComment.Text = SerNo.Comment;
txtComment.Attributes.Add("onblur", "UpdateSerialComment(" + SerNo.ID.ToString() + ", this.value);");
DropDownList ddlReasons = (e.Row.FindControl("ddlReasons") as DropDownList);
DataSet dsReasons = DataUtils.GetUnapprovedReasons(Company.Current.CompanyID, "", true, "DBRIEF");
ddlReasons.DataSource = dsReasons;
ddlReasons.DataTextField = "Description";
ddlReasons.DataValueField = "Description";
ddlReasons.DataBind();
ddlReasons.Items.Insert(0, new ListItem("Reason"));
}
}
How to I create an update function for a dropdownlist?
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
string sel = ddlReasons.SelectedValue.ToString();
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; //can't find sel value
SerNo.Update();
}
Dropdownlist:
<asp:DropDownList ID="ddlReasons" runat="server" OnSelectedIndexChanged="DDLReasons_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
I created an OnSelectedIndexChanged function to get the selected value. But how do I then save that value? Is there a way to pass it into the UpdateSerialReason function?
Just move the string sel declaration outside the scope of DDLReasons_SelectedIndexChanged and get the Text of the SelectedItem since it's included in your data source.
private string sel;
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
sel = ddlReasons.SelectedItem.Text;
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; // Should now be available
SerNo.Update();
}
The way you had it previously it was only available in the local scope, i.e, inside the method in which it was being declared and used.
You can get selected value when you call your function:
UpdateSerialReason(/*Some SerNoID*/ 123456, ddlReasons.SelectedValue)
You will lose your value after postback is done if you save value to variable as Equalsk suggested. If you need to use your value on the other page you can save it in session.
If you are working within one asp.net page you can do as I suggested above. Then you can skip the postback on your DropDownList and call UpdateSerialReason when you need :)
And you might want to add property ViewStateMode="Enabled" and EnableViewState="true"

how to change drop down list based on gridview selection

I have a drop down list which will load up with a series of customer ID numbers. I then have a gridview control on my page with the select hyperlink. When i click on the link to select the row in gridview i would like my dropdown to change to that number.
Below is what i have tried but doesn't work:
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (!GridView1.SelectedIndex.Equals(-1))
{
DropDownList ddl;
ddl = (DropDownList)form1.FindControl("ddl_Customers");
ddl.SelectedValue = (String)GridView1.SelectedDataKey.Values[0];
}
}
Handle the SelectedIndexChanged event for GridView1
void GridView1_SelectedIndexChanged(Object sender, EventArgs e) {
ddl_Customers.SelectedValue = GridView1.SelectedDataKey.Value.ToString();
}
You can directly use GridView1.SelectedValue.ToString() for this. To use that, you should define a datakeyname like this: <asp:Gridview DataKeyNames="CustomerID">
Then all you need is this:
void GridView1_SelectedIndexChanged(Object sender, EventArgs e) {
ddl_Customers.SelectedValue = GridView1.SelectedValue.ToString();
}

How to retrieve text from text box after postback?

I have some textbox's who's values are all empty when i try retrieve there values from the behind code after a post back submit.
My submit button:
<ICCM:ICCMImageButton ID="btnSubmit" runat="server" meta:resourcekey="btnResSubmit" onclick="btnSubmit_Click" PostBack="true" style="float:right; padding-right:5px;" TabIndex="23"/>
Behind C# code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
//code
objCmd.Parameters.Add("#FirstName", SqlDbType.NVarChar, 50).Value = txtFName.Text.ToString();
//more code
}
Page load:
btnSubmit.ClickScript = "if(ValidatePage() == false){return false}; this.disabled = true; document.getElementById(this.getAttribute('ControlID') + 'Text').innerHTML = '" + Resources.ICCMCPortal.Submitting + "';";
OnInt:
btnSubmit.Page = this.Page;
The text value is always "" unless i pre populated the textbox in the page load then the text will be that regardless if i made a change to it.
Set you textbox values inside here:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetTextboxValues();
}
}
This way the wont be reset on postback.

Rad Grid Not Selecting Row On Row Select

I have a Rad Grid that I bind a data source to in the Page Load. I am trying to then capture the row that is selected when the user clicks a row. I have successfully done this with a Rad Grid that has a data source set in the markup. Is it possible to do this with a grid with a dynamically set data source.
Markup
<telerik:RadGrid ID="rgTable" runat="server" OnSelectedIndexChanged="rgTable_OnSelectedIndexChanged">
<ClientSettings EnableRowHoverStyle="true" EnablePostBackOnRowClick="true">
<Selecting AllowRowSelect="true" />
</ClientSettings>
</telerik:RadGrid>
C#
protected void Page_Load(object sender, EventArgs e)
{
int id = Convert.ToInt32(Request.QueryString["ID"]);
ConnString = Connections.Search(0, 999999, null, null, null, id, null, null, null, null, null)[0].Connection_String;
StoreTableAndViewNames();//This method sets arrTables with ArrayList
rgTable.DataSource = arrTables;
rgTable.DataBind();
}
protected void rgTable_OnSelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (rgTable.SelectedItems.Count > 0)//This test is failing
{
GridDataItem item = (GridDataItem)rgTable.SelectedItems[0];
string table = item.Cells[0].ToString();
StoreColumnNames(table);
rgColumn.DataSource = arrColumns;
rgColumn.DataBind();
}
}
catch (Exception ex)
{
errorlbl.Text = ex.ToString();
}
}
In your code, Data is bind to rgTable on ever page load.
As the result, when a row is selected at client side, data is bind torgTable again before OnSelectedIndexChanged is fired.
The quick fixes is not to bind rgTable on post back.
protected void Page_Load(object sender, EventArgs e)
{
....
if (!IsPostBack)
{
rgTable.DataSource = arrTables;
rgTable.DataBind();
}
}
However, preferred method is to use NeedDataSource event
If you bind data in NeedDataSource event, RadGrid knows when & where to look for data if it is needed.
protected void rgTable_OnNeedDataSource(object sender,
GridNeedDataSourceEventArgs e)
{
rgTable.DataSource = arrTables;
}

DropDownList not accepting the SelectedIndex im trying to assign

I'm having a hard time figuring this out and I hope you guys would help me.
I have a page called Index.aspx with a DropDownList that is a separate UserControl class (because it will be used in other pages). Here's the code for that:
UcSelecionarLocal.ascx:
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="UcSelecionarLocal.ascx.cs"
Inherits="QuickMassage.uc.UcSelecionarLocal" %>
<asp:DropDownList ID="ddlLocais" runat="server"
CssClass="span4 dropdown-toggle" AutoPostBack="true">
</asp:DropDownList>
UcSelecionarLocal.ascx.cs:
public partial class UcSelecionarLocal : UserControl {
protected void Page_Load(object sender, EventArgs e) {
if (!this.IsPostBack) {
PreencherLocais();
}
}
private void PreencherLocais() {
ddlLocais.Items.Clear();
ddlLocais.Items.Add(new ListItem("Selecione", "0"));
ControleLocal controle = new ControleLocal();
DataTable tab = controle.ListarLocais();
foreach (DataRow row in tab.Rows) {
ddlLocais.Items.Add(new ListItem(row["Descricao"].ToString(),
row["ID"].ToString()));
}
}
}
This control is placed in Index.aspx and loads its values correctly. The form that it's contained in, has the action set to agendamentos.aspx. When I change the ddlist, the page is submitted to the forms action page, as it should be.
On the other page the problems begin: I get the parameters posted to this page and one of them is the ddlist value. In the immediate window, I check the value and it's there, let's say that it is 1.
To make long story short, I have this code:
agendamentos.aspx.cs:
protected void Page_Load(object sender, EventArgs e) {
DropDownList locais = ObterComponenteListaLocais();
try {
locais.SelectedIndex =
int.Parse(HttpContext.Current.Request["ucSelLocal$ddlLocais"]);
}
While debugging, I see that locais.SelectedIndex is -1. After the assignment it remains -1. The page loads and then I change the ddlist value again to 2. When debugging the same code above, I see that the locais.SelectedIndex is now 1. Again, setting it to 2, as it would normally be, produces no effect. If I change the ddlist again to 3, the SelectedIndex becomes 2 and does not take the value 3.
In other words: the value of the index in a newly loaded page is the value of the page that was loaded before.
Could you guys help me?
This is because the Page_Load event is firing in your page before the user control is loading. Do this:
public partial class UcSelecionarLocal : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void PreencherLocais()
{
ddlLocais.Items.Clear();
ddlLocais.Items.Add(new ListItem("Selecione", "0"));
ControleLocal controle = new ControleLocal();
DataTable tab = controle.ListarLocais();
foreach (DataRow row in tab.Rows)
{
ddlLocais.Items.Add(new ListItem(row["Descricao"].ToString(), row["ID"].ToString()));
}
}
}
Then in your aspx page:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
this.idOfYourUserControl.PreencherLocais();
DropDownList locais = ObterComponenteListaLocais();
try {
locais.SelectedIndex =
int.Parse(HttpContext.Current.Request["ucSelLocal$ddlLocais"]);
}
}
Also because your question is a little confusing, an important note is that Page_Load fires before data is captured from controls that post back data. So that's a bad place to get their information because it will be what it was previously. That's why you need to create a function that fires on something like a button click that will execute after the controls data have been loaded.

Categories

Resources