Basically, what I'm trying to do is get this script set up programmatically through C#. That part is working fine.
public static void ToolDatePicker_BS(ref StringBuilder Script, string Name)
{
Script.Append(#"<input type='text' name='");
Script.Append(Name);
Script.Append("'id='");
Script.Append(Name);
Script.Append(#"'value'/>");
Script.Append(#"<script>");
Script.Append(#" $(function() {");
Script.Append(#"$( '#");
Script.Append(Name);
Script.Append(#"' ).datepicker({");
Script.Append(#"showOn: 'button',");
Script.Append(#"buttonImage: './calendarFull.png' ,");
Script.Append(#"buttonImageOnly: true");
Script.Append(#"});");
Script.Append(#"});");
Script.Append(#"</script>");
}
Then after dynamically adding the script with the textbox object into the html, I need to call the textbox object to get and set text into it.
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
MyDatePicker.ToolDatePicker_BS(ref sb, "StartDateTextBox");
StartDateTextBoxPH.Text = sb.ToString();
StartDateTextBoxText = StartDateTextBox.Text();//This is the area with the problem.
}
Obviously since I defined the StartDateTextBox within quotes the compiler isn't gonna know it's a object now so I'm getting this error.
The name 'StartDateTextBox' does not exist in the current context
I think StartDateTextBox.Text would be a property.
How about removing those brackets:
StartDateTextBoxText = StartDateTextBox.Text;
Related
I am trying to add JavaScript to a page using ClientScriptManager but the script does not get added to the page. 'trendsTable' contains an asp:Gridview and its display is set to none, but on click of 'RequestReport' I want data bound to the gridview, which dataTabletester does, and then for the display of 'trendsTable' to be set to table.
protected void RequestReport_Click(object sender, EventArgs e)
{
//method to bind data to table
dataTabletester();
//insert script to make table visible
String csname1 = "PopupScript";
Type cstype = this.GetType();
//Get a Client ScriptManager reference from Page Class
ClientScriptManager cs = Page.ClientScript;
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
string script = "function() {document.getElementById('trendsTable').style.display = \"table\";}";
StringBuilder cstext1 = new StringBuilder();
cstext1.Append("<script type=text/javascript>");
cstext1.Append(script);
cstext1.Append("</script>");
cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());
}
}
Thanks to anyone who can provide any help.
You are defining a function but not calling it. Change:
string script = "function() {document.getElementById('trendsTable').style.display = \"table\";}";
to
string script = "document.getElementById('trendsTable').style.display = \"table\";";
I got stuck here,
i have dynamic table that i want to print. So i make session to pass it into web control.
Unfortunately, it doesn't run smooth.
Here are my code :
protected void bt_print_click(object sender, EventArgs e)
{
StringWriter sw = new StringWriter();
HtmlTextWriter w = new HtmlTextWriter(sw);
panelBilling.RenderControl(w);
string s = sw.GetStringBuilder().ToString();
Session["ctrl"] = s;
ClientScript.RegisterStartupScript(this.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx?rep=1','PrintMe','height=680px,width=1024px,scrollbars=1');</script>");
}
And the Print.aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
Control ctrl = (Control)Session["ctrl"];
PrintHelper.PrintWebControl(ctrl);
}
I always got error message :
"Unable to cast object of type 'System.String' to type
'System.Web.UI.Control'."
on
(Control)Session["ctrl"]
part. I have use this method many time and no problems before. Anyone has any idea? Thanks.
This just doesn't make sense, casting a string value to a Control.
As far as I can see, you are not inserting a Control into the Sessiosn, not even the Control.ToString() value, which also wouldn't be working.
Before continuing, it might be usefull to check which type is retrieved from the Session without casting anything (remark: this is only possible with .NET 3.5 or higher):
var sessionValue = Session["ctrl"];
When doing so, you will find out the value is of type object, containing the value:
"<div>\r\n\r\n</div>"
The above output is not a Control, but a string/html value.
There are two solution paths which u can follow:
Change the "SET" call on the Session
Change the "GET" call on the Session
In the second example, you keep to the fact that you are inserting a string and therefor you would like to read out that string value:
string sessionValueAsString = string.Empty;
Object sessionValue = Session["ctrl"];
if (sessionValue != null)
sessionValueAsString = sessionValue.ToString();
The above example could suit ur needs, never the less I'm guessing you are in the need to save an object of type "Control" in the session. This can be achieved like so:
MyControl myControl = new MyControl {Title = "My custom control"};
Session["myControl"] = myControl;
// Read the Session value cross Postback
MyControl mySessionControl = (MyControl)Session["myControl"];
Apart from the above example, I'm not 100% sure what you are trying to do.
My guess is you made a mistake inserting the wrong value in the Session.
One remark: I'm not a fan of storing the WebControls in the session, it would be cleaner to store your data objects in the Session (e.g. store a Customer class instead of the CustomerUserControl, this way you can read out the Session and populate the required controls using the data found in the Session).
I have an app where the user logins to a list of textboxs where the users can write in them save the data then close the app and when they open it the data is still in the textboxes.
I have been researching .txt and .xml to see which is the best format to use. I have also researched XML Serialization and what code goes in the .xml file but I'm a bit lost with do I have to change the name of the textboxes so that the data loads in the right box? Theres about 15 textboxes on the page itselfs.
I have added using System.Xml.Serialization; to my form.
Also when the user logins in it open an existing form and when the user logouts it just closes the form.
I'm a bit confused on how to load the page with all the data showing, saving the data(Iv created a save button for the textbox page) and also reading the file isn't reading and loading the same?
I'm using visual studio 2012 Winforms c#
You could use the attributes for the XML and name it from the user login.
static public void CreateFile(string username)
{
XmlWriter xmlW = XmlWriter.Create(username + ".xml");
xmlW.WriteStartDocument();
xmlW.WriteStartElement("Listofboxs");
//add the box following this canvas
xmlW.WriteStartElement("box");
xmlW.WriteAttributeString("nameofbox", "exampleName");
xmlW.WriteAttributeString("valueofbox", "exampleValue");
xmlW.WriteEndElement();
//
xmlW.WriteEndElement();
xmlW.WriteEndDocument();
xmlW.Close();
}
this will allow you to create the first file with the username.
Second, to display these informations when reloading your application, here's some code:
static public Dictionary<string, string> getBoxValue(string username)
{
Dictionary<string, string> listofbox = new Dictionary<string, string>();
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(#"./" + username + ".xml");
XmlNode root = xmldoc.DocumentElement;
foreach (XmlNode box in root)
{
listofbox.Add(box.Attributes[0].Value.ToString(),box.Attributes[1].Value.ToString());
}
return listofbox;
}
For each node, the dictionnary will add a pair of string the name of the box and its value.
You can use it to fill your boxes.
I know this code may be a little unefficiency (should use "using" and such) but I hope it could help you.
I can't understanding ur problem completely. show the coding of your program what you want.
just try when your page is loading clear all textbox data.
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = string.Empty;
}
To read and write the xml-file you can add a dataset to your project, where you define two columns. One column for the name of the textbox and another one for the value. On the dataset you can use the Methods WriteXml and ReadXml to read and write.
To load the xml at startup you have to subscribe for the load-event of the form. And in the Formclosing-event you can write your data.
public Form1()
{
this.Load += OnLoad();
this.FormClosing += OnFormClosing();
}
private void OnLoad(object sender, EventArgs e)
{
// Read Data from Xml with the dataset (dataset.Readxml...)
}
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
// Write the Data from the textboxes into the xml (dataset.writexml...)
}
To set the values of the textboxes in the load-part you can use the following code:
TextBox tb = this.Controls.Find("buttonName", true);
if(tb != null)
// set the value for the tb
In button click event I am writing this code.(code behind).I know button click event
protected void button_click()
{
string s1 = "Computer";
StringBuilder sb = new StringBuilder();
sb.Append(#"<script language='javascript'>");
sb.Append("document.write('<table><tbody>')";);
sb.Append("document.write('<tr><td>Information</td></tr>')";);
if(s1 == "Computer" )
{
sb.Append("<tr><td>s1</td></tr>");
}
sb.Append("document.write('</tbody></table>')";);
sb.Append(#"</script>");
}
It is working but I want value of s1 not s1.I know javascript is a client side programing.I wrote this function in button click event.How can pass value of s1 that is computer to table's cell
simply
sb.Append("document.write('<tr><td>" + s1 + "</td></tr>');");
Have you tried
if(s1 == "Computer" )
{
sb.Append("<tr><td>"+s1+"</td></tr>");
}
You could change this line to:
sb.Append("<tr><td>" + s1 + "</td></tr>");
Your code is a bit irrelevant to the question you're asking. Your error has already been fixed by previous answers. But I will try to expand the asnwer further. If you wish to pass some value from C# to JavaScript, there're different methods.
1) You could make a protected method in a codebehind file and call it from your .aspx file, like
my.aspx
<script type="text/javascript">
var x = '<%= GetMyValue() %>';
DoFooWithX(x);
</script>
my.aspx.cs
protected string GetMyValue()
{
return "example";
}
2) If you wish to execute some JavaScript once page finishes loading, you could also do it from your codebehind like this
my.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string myScript = string.Format("myVar = '{0}';", GetMyVarValue());
ScriptManager.RegisterStartupScript(this, this.GetType(), "MyVarSetter", myScript, true);
}
private string GetMyVarValue()
{
return "example";
}
I am trying to filter an listbox with text from a textbox, realTime.
Here is the code:
private void SrchBox_TextChanged_1(object sender, EventArgs e)
{
var registrationsList = registrationListBox.Items.Cast<String>().ToList();
registrationListBox.BeginUpdate();
registrationListBox.Items.Clear();
foreach (string str in registrationsList)
{
if (str.Contains(SrchBox.Text))
{
registrationListBox.Items.Add(str);
}
}
registrationListBox.EndUpdate();
}
Here are the issues:
When I run the program i get this error: Object reference not set to an instance of an object
If I hit backspace, my initial list is not shown anymore. This is because my actual list of items is now reduced, but how can I achieve this?
Can you point me in the right direction?
It's hard to deduct just from the code, but I presume your filtering problem born from the different aspects:
a) You need a Model of the data shown on ListBox. You need a colleciton of "Items" which you hold somewhere (Dictionary, DataBase, XML, BinaryFile, Collection), some kind of Store in short.
To show the data on UI you always pick the data from that Store, filter it and put it on UI.
b) After the first point your filtering code can look like this (a pseudocode)
var registrationsList = DataStore.ToList(); //return original data from Store
registrationListBox.BeginUpdate();
registrationListBox.Items.Clear();
if(!string.IsNullOrEmpty(SrchBox.Text))
{
foreach (string str in registrationsList)
{
if (str.Contains(SrchBox.Text))
{
registrationListBox.Items.Add(str);
}
}
}
else
registrationListBox.Items.AddRange(registrationsList); //there is no any filter string, so add all data we have in Store
registrationListBox.EndUpdate();
Hope this helps.
Something like this might work for you:
var itemList = registrationListBox.Items.Cast<string>().ToList();
if (itemList.Count > 0)
{
//clear the items from the list
registrationListBox.Items.Clear();
//filter the items and add them to the list
registrationListBox.Items.AddRange(
itemList.Where(i => i.Contains(SrchBox.Text)).ToArray());
}
Yes that was the answer to filtering. (modified a bit). I had the info in a text file. This is what worked for me
FileInfo registrationsText = new FileInfo(#"name_temp.txt");
StreamReader registrationsSR = registrationsText.OpenText();
var registrationsList = registrationListBox.Items.Cast<string>().ToList();
registrationListBox.BeginUpdate();
registrationListBox.Items.Clear();
if (!string.IsNullOrEmpty(SrchBox.Text))
{
foreach (string str in registrationsList)
{
if (str.Contains(SrchBox.Text))
{
registrationListBox.Items.Add(str);
}
}
}
else
while (!registrationsSR.EndOfStream)
{
registrationListBox.Items.Add(registrationsSR.ReadLine());
}
registrationListBox.EndUpdate();
It seems that the error:
Object reference not set to an instance of an object
is from somewhere else in my code, can't put my finger on it.
If able, store everything in a dictionary and just populate it from there.
public partial class myForm : Form
{
private Dictionary<string, string> myDictionary = new Dictionary<string, string>();
//constructor. populates the items. Assumes there is a listbox (myListbox) and a textbox (myTextbox), named respectively
public myForm()
{
InitializeComponent();
myDictionary.Add("key1", "item1");
myDictionary.Add("key2", "My Item");
myDictionary.Add("key3", "A Thing");
//populate the listbox with everything in the dictionary
foreach (string s in myDictionary.Values)
myListbox.Add(s);
}
//make sure to connect this to the textbox change event
private void myTextBox_TextChanged(object sender, EventArgs e)
{
myListbox.BeginUpdate();
myListbox.Items.Clear();
foreach (string s in myDictionary.Values)
{
if (s.Contains(myListbox.Text))
myListbox.Items.Add(s);
}
myListbox.EndUpdate();
}
}
I would do it like this:
private List<string> registrationsList;
private void SrchBox_TextChanged_1(object sender, EventArgs e)
{
registrationListBox.BeginUpdate();
registrationListBox.Items.Clear();
var filteredList = registrationList.Where(rl => rl.Contains(SrchBox.Text))
registrationListBox.Items.AddRange();
registrationListBox.EndUpdate();
}
Just remember to populate registrationsList the first time you fill your listbox.
Hope this helps.
it was a very hard issue for me, but I found a workaround (not so simple) that works fine for me.
on aspx page:
<input id="ss" type="text" oninput="writeFilterValue()"/>
<asp:HiddenField ID="hf1" runat="server" Value="" ClientIDMode="Static" />
I need HTML input type because of "oninput" function, that is not availiable on classic asp.net controls. The writeFilterValue() function causes a postback that filters values of a given ListBox (in code-behind).
I've defined this two javascript function:
<script type="text/javascript">
function writeFilterValue() {
var bla = document.getElementById("ss").value;
$("#hf1").val(bla)
__doPostBack();
}
function setTboxValue(s) {
document.getElementById('ss').value = s;
document.getElementById('ss').focus();
}
</script>
You can now use postback on code-behind to capture hf1 value, every time some single Character is typed on inputbox.
On code-behind:
If IsPostBack Then
FiltraLbox(hf1.Value)
End If
The function FiltraLbox(hf1.Value) changes datasource of Listbox, and rebind it:
Public Sub FiltraLbox(ByVal hf As String)
If hf <> "" Then
' change datasource here, that depends on hf value,
ListBox1.DataBind()
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "text", setTboxValue('" + hf + "');", True)
End If
End Sub
At the end I call the function setTboxValue(), that rewrites the input text value lost on postback, and puts the focus on it.
Enjoy it.