I have 2 textboxes turn into jquery datepickers and some folder names like 09-13-2014, 09-14-2014 and 09-15-2014, how can I get all folder names from the selected dates on button click and place it on a treeview? I'm new to this, not yet familliar on the back end coding.
Here's my datepickers:
<script type="text/javascript">
$(function () {
$("[id$=txtDate1]").datepicker({
dateFormat: 'mm-dd-yy',
showOn: 'button',
buttonImageOnly: true,
buttonImage: 'Images/calendar.png'
});
});
</script>
<p>
From: <asp:TextBox ID="txtDate1" runat="server" ReadOnly = "true"></asp:TextBox>
To:<asp:TextBox ID="txtDate2" runat="server" ReadOnly = "true"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Search" />
</p>
I supposed that you datepicker working fine and it showing the calender.
<p>
From:
//you should delete ReadOnly = "true" on textboxes
<asp:TextBox ID="txtDate1" runat="server"></asp:TextBox>
To:<asp:TextBox ID="txtDate2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Search" OnClick="Button1_Click" />
</p>
<asp:TreeView ID="TreeView1" runat="server">
</asp:TreeView>
on code behinde write this codes. you can go to codebehind by rightclick on your page and then selecting view code.
protected void Button1_Click(object sender, EventArgs e)
{
var start = Convert.ToDateTime(txtDate1.Text);
var end = Convert.ToDateTime(txtDate2.Text);
if (end < start)
return;
var folderNamelst = GetListOfExsistingFolderName(start, end);
AddNodes(folderNamelst);
}
private IEnumerable<string> GetListOfExsistingFolderName(DateTime startDate, DateTime endTime)
{
var mainFolderPath = Server.MapPath("~/Folders");
var folderNamelst = new List<string>();
var day = startDate;
do
{
if (Directory.Exists(mainFolderPath + "\\" + day.ToString("MM-dd-yyyy")))
folderNamelst.Add(day.ToString("MM-dd-yyyy"));
day = day.AddDays(1);
} while (day <= endTime);
return folderNamelst;
}
private void AddNodes(IEnumerable<string> data)
{
TreeView1.Nodes.Clear();
var root = new TreeNode("Folders");
foreach (var d in data)
{
var treechild = new TreeNode(d);
root.ChildNodes.Add(treechild);
}
TreeView1.Nodes.Add(root);
}
Related
I'm struggling a lot and I hope someone can help me please.
I have a 4 dropdownlists, a search button and a normal gridview with a basic SQLdataConnection.
The SQLdataConnection is a stored procedure that retrieves 3 tables based on 4 parameters. These 3 tables are then joined together into the gridview.
BUT
One of the dropdownlists has the options of Total, Fast and Slow. So based on which option the user chooses the respective table should be loaded into the gridview when the search button is pressed. (So if total is chosen, the total table should be loaded into the gridview)
I don't know if the SQLdataConnection should be changed with each option to show only the appropriate table.
Below is a copy of the html of the dropdowns and gridview as well as the code behind.
<tr>
<td style="text-align: right" class="pad-right-0">
<asp:DropDownList ID="selSeconds" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:DropDownList ID="selHours" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:DropDownList ID="selMerchantId" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:DropDownList ID="selTableType" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:Button ID="btnSearch" runat="server" CssClass="btn btn-primary btn-danger tip-s medium grey" ValidationGroup="Search" OnClick="btnSearch_Click" Text="<%$Resources:Resource, btnSearch %>" />
<asp:ImageButton ID="btnExportToExcel" runat="server" CssClass="btn btn-primary btn-danger tip-s medium grey" ValidationGroup="Search" onclick="btnExportToExcel_Click" Text="Export to excel" ImageUrl="images/Excel.png" AlternateText="<%$Resources:Resource, lblExportExcel %>"
CausesValidation="false" />
<asp:RequiredFieldValidator ID="rqrdMerchantId" runat="server" ErrorMessage="<%$Resources:Resource, lblRequired %>" ControlToValidate="selMerchantId" ForeColor="Red" />
</td>
</tr>
</table>
<asp:HiddenField ID="hdnMerchantId" runat="server" Value="0" />
<asp:GridView ID="gridSpeedAnalysis" runat="server" DataSourceID="gridSqlConnection">
</asp:GridView>
<asp:SqlDataSource ID="gridSqlConnection" runat="server"></asp:SqlDataSource>
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserName"] == null || Session["UserType"] == null)
{
Response.Redirect("Login.aspx");
}
LoadDropDowns();
}
private void LoadDropDowns()
{
System.Web.UI.WebControls.ListItem item;
selSeconds.Items.Insert(0, new System.Web.UI.WebControls.ListItem("Select Second", "0"));
int index = 1;
for (int Second = 0; Second <= 10; Second++)
{
System.Web.UI.WebControls.ListItem li = new System.Web.UI.WebControls.ListItem(Second.ToString(), Second.ToString());
selSeconds.Items.Insert(index, li);
index++;
}
item = selSeconds.Items.FindByValue(DateTime.Now.Year.ToString());
selSeconds.SelectedIndex = selSeconds.Items.IndexOf(item);
if (Session["UserType"] != null && (Session["UserType"].ToString().ToLower() == "System Administrator".ToLower()))
{
selMerchantId.DataSource = BOL.MerchantGroup.Load();
selMerchantId.DataTextField = "Description";
selMerchantId.DataValueField = "MerchantId";
selMerchantId.DataBind();
selMerchantId.Items.Insert(0, new System.Web.UI.WebControls.ListItem { Value = "0", Text = "Select Group" });
rqrdMerchantId.InitialValue = "0";
}
else if (Session["UserType"].ToString().ToLower() == "Head Office".ToLower())
{
BOL.MerchantGroup group = new BOL.MerchantGroup(int.Parse(hdnMerchantId.Value));
selMerchantId.Items.Insert(0, new System.Web.UI.WebControls.ListItem { Value = hdnMerchantId.Value, Text = group.Description });
}
DataTable dt = BOL.Merchant.GetDropdownByMerhcantGroupId(int.Parse(Session["MerchantGroupId"].ToString()));
selMerchantId.DataSource = dt;
selMerchantId.DataTextField = "Name";
selMerchantId.DataValueField = "MerchantId";
selMerchantId.DataBind();
selTableType.Items.Insert(0, new System.Web.UI.WebControls.ListItem {Text = "Total"});
selTableType.Items.Insert(0, new System.Web.UI.WebControls.ListItem {Text = "Fast" });
selTableType.Items.Insert(0, new System.Web.UI.WebControls.ListItem {Text = "Slow" });
}
protected void btnSearch_Click(object sender, EventArgs e)
{
}
Here's a little thing i want to achieve. I have an asp.net FileUpload and a textbox. When a user clicks the fileUpload and selects a picture from his/her computer/device, i want the image name to be immediately displayed in a textbox before submitting . Here is what i have tried
<asp:FileUpload ID="Upload" runat="server" ClientIDMode="Static" />
<asp:TextBox ID="txtImage" runat="server" ClientIDMode="Static">
$('#Upload').change(function () {
var filename = $(this).val();
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex > 0) {
filename = filename.substring(lastIndex + 1);
}
$('txtImage').val(filename);
});
It still cant get it displayed. wHAT AM I MISING PLEASE
you are missing # in $("txtImage"). This should be like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
console.log("ready!");
$('#Upload').change(function () {
var filename = $(this).val();
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex > 0) {
filename = filename.substring(lastIndex + 1);
}
$('#txtImage').val(filename);
});
});
</script>
<asp:FileUpload ID="Upload" runat="server" ClientIDMode="Static" />
<asp:TextBox ID="txtImage" runat="server" ClientIDMode="Static"></asp:TextBox>
TextBox txtImage does not have a closing tag.
<asp:TextBox ID="txtImage" runat="server" ClientIDMode="Static"/>
I am trying to deserialize JSON to C# list. I have the Jquery code as,
$(document).ready(function () {
$("#btn_check").click(function () {
var str="";
x = $("#frm").serializeArray();
$("#Label1").empty();
$.each(x, function (i, field) {
// $("#Label1").append(field.name + ":" + field.value + " ");
str = str + field.name + ":" + field.value + " ";
});
var jsonstr=JSON.stringify(str); });
});
after stringify, I get something weird as jsonstr=
__VIEWSTATE:/wEPDwUKLTg1MjI5MDU0MWQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFjIFB2NoZWNrXzAFB2NoZWNrXzEFB2NoZWNrXzIFB2NoZWNrXzMFB2NoZWNrXzQFB2NoZWNrXzUFB2NoZWNrXzYFB2NoZWNrXzcFB2NoZWNrXzgFB2NoZWNrXzkFCGNoZWNrXzEwBQhjaGVja18xMQUIY2hlY2tfMTIFCGNoZWNrXzEzBQhjaGVja18xNAUIY2hlY2tfMTUFCGNoZWNrXzE2BQhjaGVja18xNwUIY2hlY2tfMTgFCGNoZWNrXzE5BQhjaGVja18yMAUIY2hlY2tfMjEFCGNoZWNrXzIyBQhjaGVja18yMwUIY2hlY2tfMjQFCGNoZWNrXzI1BQhjaGVja18yNgUIY2hlY2tfMjcFCGNoZWNrXzI4BQhjaGVja18yOQUIY2hlY2tfMzAFCGNoZWNrXzMxBQhjaGVja18zMgUIY2hlY2tfMzMFCGNoZWNrXzM0BQhjaGVja18zNQUIY2hlY2tfMzYFCGNoZWNrXzM3BQhjaGVja18zOAUIY2hlY2tfMzkFCGNoZWNrXzQwBQhjaGVja180MQUIY2hlY2tfNDIFCGNoZWNrXzQzBQhjaGVja180NAUIY2hlY2tfNDUFCGNoZWNrXzQ2BQhjaGVja180NwUIY2hlY2tfNDgFCGNoZWNrXzQ5s98N0sYArkR3uk7Sb4bJWOocOpU= __VIEWSTATEGENERATOR:172284EE __EVENTVALIDATION:/wEWNAKauo6nDAK5rJ0YAp7D/4IGAoPa4e0LAujww9gBAs2HpsMHArKeiK4NApe16pgDAvzLzIMJApH2i8IBAvaM7qwHAp7Dv7UBAp7Dq9oIAp7Dl/8PAp7Dg6QHAp7Dj6IEAp7D+8YLAp7D5+sCAp7D05AKAp7Dn9wLAp7Di4EDAoPaoaAHAoPajcUOAoPa+ekFAoPa5Y4NAoPa8YwKAoPa3bEBAoPaydYIAoPatfsPAoPagccBAoPa7esIAujwg4sNAujw768EAujw29QLAujwx/kCAujw0/cPAujwv5wHAujwq8EOAujwl+YFAujw47EHAujwz9YOAs2H5vUCAs2H0poKAs2Hvr8BAs2HquQIAs2HtuIFAs2HoocNAs2HjqwEAs2H+tALAs2HxpwNAs2HssEEAvCFnqIPppJbhAvF8AzSoMd/uZfiRXpzWu0= check_0:on check_1:on check_2:on check_3:on check_4:on check_5:on check_6:on check_7:on check_8:on check_9:on check_10:on check_11:on check_12:on check_13:on check_14:on check_15:on check_16:on check_17:on check_18:on check_19:on check_20:on check_21:on check_22:on check_23:on check_24:on check_25:on check_26:on check_27:on check_28:on check_29:on check_30:on check_31:on check_32:on check_33:on check_34:on check_35:on check_36:on check_37:on check_38:on check_39:on check_40:on check_41:on check_42:on check_43:on check_44:on check_45:on check_46:on check_47:on check_48:on check_49:on
check_0 to check_1 are the dynamically created checkboxes and I want to get their values in C# as list or in any form to interpret and push them into Database.
asp.net:
<form id="frm" runat="server">
<asp:Panel ID="pnl_seat" runat="server">
<asp:PlaceHolder ID="plhdr_seat" runat="server">
checkboxes are dynamically created here
</asp:PlaceHolder>
<br />
<button id="btn_check" type="button">Serialize form values</button>
<asp:Button ID="btn_submit" runat="server" Text="Submit" OnClick="btn_submit_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
</asp:Panel>
</form>
picture:
C# code:
using Newtonsoft.Json;
class abc // some class
{
protected void btn_submit_Click(object sender, EventArgs e)
{
List<Test> myDeserializedObjList = (List<Test>) Newtonsoft.Json.JsonConvert.DeserializeObject(Request["jsonstr"], typeof(List<Test>));
}
}
the above code I got it from codeproject.com.
But on running this code, I am getting an exception that "str" as "null". How to push the label1 or str to server side? Help me please.
Could you paste more code? It's hard to find any issues from the limited source code.
You may send the str to server using an ajax request:
$.get('your url', {str: str})
By the way, It seems the str is not a valid JSON string. str = JSON.strigify(x) will stringify the object to a JSON string.
Try this:
```
$(document).ready(function () {
$("#btn_check").click(function () {
var x = $("#frm").serializeArray();
$("#Label1").empty().text(JSON.stringify(x));
});
});
using Newtonsoft.Json;
class abc // some class
{
protected void btn_submit_Click(object sender, EventArgs e)
{
List<Test> myDeserializedObjList = (List<Test>) Newtonsoft.Json.JsonConvert.DeserializeObject(Label1.Text, typeof(List<Test>));
}
}
```
JQUERY:
$(document).ready(function () {
$("#btn_check").click(function () {
var str = "";
x = $("#frm").serializeArray();
str = JSON.stringify(x);
// $("#HiddenField1").Value(str);
$('#<%=hdnSelectedTicket.ClientID %>').val(str);
<%-- $('#<%=hdnSelectedTicket.ClientID %>')--%>
});
});
ASP.NET:
<form id="frm" runat="server">
<asp:HiddenField ID="hdnSelectedTicket" runat="server" />
<asp:Panel ID="pnl_seat" runat="server">
<asp:PlaceHolder ID="plhdr_seat" runat="server"></asp:PlaceHolder>
<br />
<button id="btn_check" type="button">Serialize form values</button>
<asp:Button ID="btn_submit" runat="server" Text="Submit" OnClick="btn_submit_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
</asp:Panel>
</form>
C#:
using Newtonsoft.Json;
protected void btn_submit_Click(object sender, EventArgs e)
{
//string a = hdnSelectedTicket.Value;
List<Test> myDeserializedObjList = (List<Test>)Newtonsoft.Json.JsonConvert.DeserializeObject (hdnSelectedTicket.Value, typeof(List<Test>));
}
I need the client to be able to enter values into an asp TextBox that asks amount of hours they spend doing these activities. The numbers they enter run in javascript. I am having a hard time getting those values into javascript. Then have it run on button click. Thanks for any help. This is what I've got so far:
<script runat="server">
void btn_Click(object sender, EventArgs e)
{
double work = double.Parse(TextBox1.Text);
double eat = double.Parse(TextBox2.Text);
double commute = double.Parse(TextBox3.Text);
double tv = double.Parse(TextBox4.Text);
double sleep = double.Parse(TextBox5.Text);
double total = work + eat + commute + tv + sleep;
if (total > 24)
{
lblmsg.Text = code();
}
}
string code()
{
return "Warning: There are only 24 hours in a day!";
}
</script>
Java script:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var work = document.getElementById('<%=TextBox1.ClientID%>').value;
var eat = document.getElementById('<%=TextBox2.ClientID%>').value;
var commute = document.getElementById('<%=TextBox3.ClientID%>').value;
var tv = document.getElementById('<%=TextBox4.ClientID%>').value;
var sleep = document.getElementById('<%=TextBox5.ClientID%>').value;
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', work],
['Eat', eat],
['Commute', commute],
['Watch TV', tv],
['Sleep', sleep]
]);
var options = {
title: 'My Daily Activities',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
</script>
Text Boxes and Button:
Work:<asp:TextBox ID="TextBox1" runat="server" Text="11"/><asp:Label ID="lblmsg" runat="server" color="red" BackColor="red" Font-Size="XX-Large"/><br />
Eat:<asp:TextBox ID="TextBox2" runat="server" text="2"/><br />
Commute:<asp:TextBox ID="TextBox3" runat="server" text="2"/><br />
Watch TV:<asp:TextBox ID="TextBox4" runat="server" text="2"/><br />
Sleep:<asp:TextBox ID="TextBox5" runat="server" text="7"/><br />
<asp:Button ID="btn" runat="server" Text="COMPUTE TIME" OnClick="btn_Click" />
Thanks for any help!
I think you are mixing apples and oranges here. You do not need ASP.NET or any other server side language to make basic client-side calculations. jQuery alone can do it anyway with simple HTML textboxes. Just learning using jQuery val() and it's enough.
I have 2 dropdownlists on my page. One for activity and one for sub activity. When the activity dropdownlist changes I retrieve the values for the sub activity dropdownlist . I am using a updatepanel for the second dropdownlist and the trigger is set to the first dropdownlist. This is working magicly until I leave the page to idle for a while 1-2min max. When I change the value for the activity dropdownlist(the trigger) it causes a full postback and the items for the second dropdownlist does not get populated.
Here is my code below.
Aspx
<div class="form-line">
<label>Activity</label>
<asp:DropDownList ID="ddlActivity" required="required" CssClass="chosen-select" runat="server" Width="200px" AppendDataBoundItems="true" OnSelectedIndexChanged="SelectedActivity_Changed" AutoPostBack="true" CausesValidation="false">
</asp:DropDownList>
</div>
<div class="form-line">
<label>Sub Activity</label>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlActivity" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:DropDownList ID="ddlSubActivity" runat="server" Width="200px" required="required" CssClass="chosen-select" AppendDataBoundItems="true" CausesValidation="false">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</div>
Code behind
[ToolboxItemAttribute(false)]
public partial class MyEstimatesAdd : WebPart
{
static string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
ChronoLogDataContext dc = new ChronoLogDataContext(connStr);
// Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution
// using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
// for production. Because the SecurityPermission attribute bypasses the security check for callers of
// your constructor, it's not recommended for production purposes.
// [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
public MyEstimatesAdd()
{
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
InitializeControl();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Page.Request.QueryString["Issue_ID"] != "" && Page.Request.QueryString["Issue_ID"] != null)
{
Int64 issueid = Int64.Parse(Page.Request.QueryString["Issue_ID"]);
string sCurrentUserEmail;
SPUser cuser = SPControl.GetContextWeb(Context).CurrentUser;
sCurrentUserEmail = cuser.Email;
dc = new ChronoLogDataContext(connStr);
var resource = (from r in dc.RESOURCEs
where r.Email == sCurrentUserEmail
select r).FirstOrDefault();
ddlActivity.DataSource = (from a in dc.ACTIVITY_CATEGORies
select a).ToList();
ddlActivity.DataValueField = "Activity_Category_ID";
ddlActivity.DataTextField = "Description";
ddlActivity.DataBind();
ddlActivity.Items.Insert(0, new ListItem("", ""));
}
}
}
//RUN AGAIN PRIMARY SET
protected void btnAdd_Click(object sender, EventArgs e)
{
int hours;
if (!int.TryParse(txtHours.Text, out hours))
{
throw new SPException("Hours must be a numeric value");
}
string sCurrentUserEmail;
SPUser cuser = SPControl.GetContextWeb(Context).CurrentUser;
sCurrentUserEmail = cuser.Email;
dc = new ChronoLogDataContext(connStr);
var resource = (from r in dc.RESOURCEs
where r.Email == sCurrentUserEmail
select r).FirstOrDefault();
Int64 issueid = Int64.Parse(Page.Request.QueryString["Issue_ID"]);
decimal time = decimal.Parse(hours + "." + ddlMinutes.SelectedValue.ToString(), CultureInfo.InvariantCulture);
ESTIMATE estimate = new ESTIMATE { Activity_ID = int.Parse(ddlActivity.SelectedItem.Value), Date_Captured = DateTime.Now, Estimated_Time = time, Features = txtFeatures.Text, Issue_ID = issueid, Resource_ID = resource.Resource_ID, Sub_Activity_ID = int.Parse(ddlSubActivity.SelectedItem.Value) };
dc.ESTIMATEs.InsertOnSubmit(estimate);
dc.SubmitChanges();
Close_Save();
}
protected void Close_Save()
{
HttpContext context = HttpContext.Current;
if (HttpContext.Current.Request.QueryString["IsDlg"] != null)
{
context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup()</script>");
context.Response.Flush();
context.Response.End();
}
}
protected void SelectedActivity_Changed(object sender, EventArgs e)
{
int activityid = int.Parse(ddlActivity.SelectedItem.Value);
dc = new ChronoLogDataContext(connStr);
var subactivities = (from s in dc.ACTIVITY_SUBCATEGORies
where s.Activity_Category_ID == activityid
select s).ToList();
ddlSubActivity.Items.Clear();
ddlSubActivity.DataSource = subactivities;
ddlSubActivity.DataValueField = "Activity_SubCategory_ID";
ddlSubActivity.DataTextField = "Description";
ddlSubActivity.DataBind();
ddlSubActivity.Items.Insert(0, new ListItem("", ""));
UpdatePanel1.Update();
}
}
Put both drop down lists within the same UpdatePanel or each in their own UpdatePanel, like this:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlActivity" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<div class="form-line">
<label>Activity</label>
<asp:DropDownList ID="ddlActivity" required="required" CssClass="chosen-select" runat="server" Width="200px" AppendDataBoundItems="true" OnSelectedIndexChanged="SelectedActivity_Changed" AutoPostBack="true" CausesValidation="false">
</asp:DropDownList>
</div>
<div class="form-line">
<label>Sub Activity</label>
<asp:DropDownList ID="ddlSubActivity" runat="server" Width="200px" required="required" CssClass="chosen-select" AppendDataBoundItems="true" CausesValidation="false">
</asp:DropDownList>
</div>
</ContentTemplate>
</asp:UpdatePanel>