End user add values to a dropdownlist? - c#

I'm populating a dropdownlist in c# asp.net-MVC from a SQL table using Linq2Sql. I'd like for the user to be able to enter something that isn't in the list into the drop down and have it add to the table. Is this possible?

Sounds like you need to add a radio button labeled "Other". When the user clicks the radio button a text box would appear that allows the user to input a new value that you can save to your DB and display in the drop down.
EDIT:
Quick snippet to enable the control using JavaScript:
<script language="javascript" type="text/javascript">
function radioclicked() {
textObj = document.getElementById('<NAME OF TEXT BOX');
textObj.disabled = false;
}
</script>
You can use a check box instead of a radio button so that the enabled property can be toggled.
To completely hide the text box then you will have to look into jQuery/Ajax.

Why can't we use a lightweight Add-on like www.combodropdown.info for this purpose? You can even consider AutoComplete plugin from jQuery, if your app already references jQuery.

Also a combobox will allow a user to enter a value in addition to picking from a list.

My MVC is not so so, but I assume this still applies as MVC is just model view controller.
What if you throw a drop down on your form visible=true, and a textbox on your form visible =false.
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:TextBox ID="TextBox1" runat="server" Visible="False"></asp:TextBox>
Fill your drop down:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<int> s = Enumerable.Range(1, 10).ToList();
DropDownList1.DataSource = s;
DropDownList1.DataBind();
DropDownList1.Items.Add("Other");
}
}
Add an event to handle if someone selects other. If they do make the textbox visible:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
switch (this.DropDownList1.SelectedItem.Text)
{
case "Other":
this.TextBox1.Visible=true;
break;
default:
this.TextBox1.Visible=false;
break;
}
}
Now you can enter your value and re-store back to the db.

Related

How do I disable RadButton from server-side?

I have this button in my aspx file.
<telerik:RadButton ID="btnEnable" OnClick="btnEnable_Click" runat="server" ToolTip="enable"
Text="Enable" Enabled="false" Icon-PrimaryIconUrl="~/images/icon.png">
</telerik:RadButton>
I am disabling it on client-side like this :
btnEnable.set_enabled(false);
I want to add server-side code in my aspx.cs. So when item is selected in grid, I want this button to be disabled from server-side.
function looks like this
protected void btnEnable_Click(object sender, EventArgs e)
{
if(someLogic){btnEnable must be disabled}
}
If it helps, this button can be called after item is selected in the grid.
Remember you can add ToggleStates:
MyButton.ToggleType = ButtonToggleType.CheckBox;
MyButton.ButtonType = RadButtonType.ToggleButton;
MyButton.ToggleStates.Add("Selected");
MyButton.ToggleStates.Add("Unselected");
MyButton.Checked= false; //set to unselected

how change textbox text after clicking on a button inside a gridview

i have one textbox and one button both on a gridview , when user clicks on button i want to get the textbox text and save to database then clear the text! i used code below it works fine and saves to database but cant clear the textbox why ?
protected void sendcm_Click(object sender, EventArgs e)
{
try
{
Button sendcm = (Button)sender;
GridViewRow gvrow = (GridViewRow)sendcm.NamingContainer;
int ActivityTypeID = Convert.ToInt32(activity.DataKeys[gvrow.RowIndex].Values["ActivityTypeID"].ToString());
int SourceID = Convert.ToInt32(activity.DataKeys[gvrow.RowIndex].Values["SourceID"].ToString());
TextBox tt = (TextBox)activity.Rows[gvrow.RowIndex].FindControl("cmtextbox");
if (tt.Text != "")
{
BusinessLayer.StatusComment_Table ncm = new BusinessLayer.StatusComment_Table();
ncm.Id = Convert.ToInt32(Session["ID"].ToString());
ncm.Statusid = SourceID;
ncm.Statuscommentdate = System.DateTime.Now;
ncm.Statuscommenttext = tt.Text;
ncm.Save();
tt.Text = ""; // its not working !!!!
}
}
protected void Page_Load(object sender, EventArgs e)
{
SessionLable.Text = Session["ID"].ToString();
if (!IsPostBack)
{
getData();
}
}
public void getData()
{
activity.DataSource = BusinessLayer.Activity_Table.GetByProfileData(ID, -1, activity.PageSize);
activity.DataBind();
}
You need to do this at the UI level.
Use jquery.post to call the method that saves the data.
return something back to the $.post callback to tell jquery that the post s complete,
then do something like $('#mytextfield').val('')
assuming that the text box has an ID. I am assuming this is HTML?
you might need to rebind your grid because from the code that you posted it's not clear that where are you re binding your grid.
You need to enable AjaxPostback in your page. After that, in your Page_Load logic, include the code
if(IsPostBack){...}else{...}
So you can handle the construction of UI elements depending on whether this is a fresh new view of the page or a postback (page refreshed due to user clicking the button). UI elements are sent to the browser, after that, there is no way for the server to change it except to refresh the page itself.
The manual (and the one I recommend) way is to do this via jQuery postback. As pointed out in the other answer, you'll need to setup an endpoint for the client browser to connect. After the server has done its job, return the result to the client. Then use jQuery to update the textbox.
i did this to solve my problem !
<asp:TextBox ID="cmtextbox" type="text" clientid="cmtextbox" TextMode="MultiLine" placeholder="نظر دهید..." Rows="1" style="resize:none" class="form-control" runat="server"></asp:TextBox>
<asp:Button ID="sendcm" style="margin-top:2px;" OnClick="sendcm_Click" class="btn btn-success btn-sm pull-left " OnClientClick="ClearTextbox(this)" runat="server" Text="ارسال" />
</script>
<script type="text/javascript">
ClearTextbox = function (that) {
$(that).prevUntil('div.stop', '[ClientID="cmtextbox"]').val('');
}
</script>

Hide button on drop down selection -1

I need my create button to be hidden unless a facility is selected in my dropdown. When it is at -1 message i need my button to be hidden.
Code for button
<asp:Button ID="btnCreate" runat="server" Text="Create New" Width="89px" Font-Size="X-Small" OnClick="btnCreate_Click" />
Drop down code
private void ResetForm()
{
try
{
//facility dropdown
ddlFacility2.Items.Clear();
ddlFacility2.DataSource = this.DataLayer.model.MS_spGetFacilityInfo(null).OrderBy(x => x.FacilityName);
ddlFacility2.DataTextField = "FacilityName";
ddlFacility2.DataValueField = "FacilityID";
ddlFacility2.DataBind();
ddlFacility2.Items.Insert(0, new ListItem("All Facility Records..", "-1"));
BindGrid();
}
catch (Exception ex)
{
this.SetMessage(ex.ToString(), PageMessageType.Error);
AISLogger.WriteException(ex);
}
}
in first time page load if the default value selected is -1 you can set your button visible false as default.
in your droupdown list selected index change event you can enable/dissable button based on droupdown list selected value.
Add a OnSelectedIndexChange event to your dropdown list or add a clientside event to your dropdownlist. Double Click on your ddl you will see a function named ddlFacility2_OnSelectedIndexChanged in you code behind and add the below code to it.
Add AutoPostBack=true to you ddl
protected void ddlFacility2_OnSelectedIndexChanged(object sender, EventArgs e)
{
if(ddlFacility2.SelectedIndex>-1)
{
btnCreate.Enabled = true;
}
else
{
btnCreate.Enabled = false;
}
}
You can wire up a JQuery script that can bind to your DropDownList's selected value...
In this example, the button's visibility is bound on a click from another button:
$('#Button1').bind("click", function() {
$("#Button2").hide();
});
I dont know the exact syntax to use for the binding to selected value, but the above code should be a good place to start.

Change the value of a textbox in a template field from event outside of GridView

I need to be able to change the value of a TextBox(s) in a GridView template field from a TextChanged event. So the user can enter some text in a TextBox outside of the Gridview and then the TextBox(s) in the GridView gets updated to what the user entered.
This is what I need to do:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
template_text_box1.Text( in template field ) = TextBox1.Text << (TextBox1)( outside of gridview )
}
I have tried FindControl. This needs to happen without using any of the GridView events. I am just stumped. Could someone point me in the right direction? Maybe some JavaScript?
I believe that you would want to define a separate TextBox for the display and do something like the following:
double value1;
private void template textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if textBox1.Text (Double.TryParse(textBox1.Text, out value1))
{
textBox15 = value1.ToString();
}
}
This way you can make your other TextBox outside the grid and be able to call it and set to the value that is inputted.
On the .Aspx page, in the GridView column template TextBox add a CSS class.
<asp:TextBox ID="TextBox1" runat="server" CssClass="box-to-change" Text=""></asp:TextBox>
Also on the .Aspx page add a JavaScript function that uses jQuery:
<script type="text/javascript">
function updateAllTextboxes(value)
{
$('input.box-to-change').val(value);
}
</script>
In the code-behind add the JavaScript function as a client OnChange event (will not require PostBack).
otherTextBox.Attributes["onchange"] = "updateAllTextboxes(this.value)";

RequiredValidator for Drop Down not firing (asp:dropdown populated from database)

<asp:DropDownList id="Code1" runat="server"
OnLoad="GetCode1" ValidationGroup="ValidateGroup"/>
<asp:RequiredFieldValidator ID="Code1_RequiredValidator" runat="server"
ErrorMessage="Please select a value!" ControlToValidate="Code1"
ValidationGroup="ValidateGroup" InitialValue="Select Code1!">
</asp:RequiredFieldValidator>
the drop down is populated in the code behind as shown below:
protected void GetCode1(object sender, EventArgs e)
{
if (!IsPostBack)
{
ISROManagement sroMgmt = ObjectFactory.CreateSROManagement();
List<string> code1List = QuerydBForCodes();
Code1.DataSource = codeList;
Code1.DataBind();
Code1.Items.Insert(0, "Make a selection."); //Added to be shown as the default value:
}
}
When I submit the modal pop up extender -with the default value at index 0 i.e. Make a Selection - I don't see the ErrorMessage="Please make a selection!" printed next to the drop down! So the validation does not happen.
Also in the button click which submits the modal pop up, i have a
Page.Validate("ValidateGroup");
if (!Page.IsValid) return;
However, I dont see the validation message printed next to the drop down!
In GetCode1 function replace following line:
Code1.Items.Insert(0, "Make a selection.");
To
Code1.Items.Insert(0, "");
Your drop down list must have the same ValidationGroup. Add ValidationGroup="ValidateGroup" to your drop down list
Change InitialValue from "Select Code1!" to "Make a selection."

Categories

Resources