Trying to get the value of a text box - c#

I'm creating a sql statement in c#, and I am trying to get the value from a text box in a previous form:
SqlParameter PeriodFrom = new SqlParameter("#PeriodFrom", SqlDbType.VarChar);
PeriodFrom.Value =
I am just unsure of what goes after the equals sign. I tried the form name.textbox name.

In the code behind of the form, inside the form class, you can declare a property:
public string TextBoxValue
{
get
{
return textBoxName.Text;
}
}
And you can use it with your SqlParameter like this:
SqlParameter PeriodFrom = new SqlParameter("#PeriodFrom", SqlDbType.VarChar);
PeriodFrom.Value = FormClassName.TextBoxValue;
Edit:
This wouldn't work since the Form class object is not static and it wouldn't persist. To make this work, you would need to make changes to the Program class. You would need to add a static Data member in the Program class like this:
public static FormClassName form;
and would need to pass this in the main method as below:
form = new FormClassName();
Application.Run(form);
And in the SQLParameter you can pass it like this:
SqlParameter PeriodFrom = new SqlParameter("#PeriodFrom", SqlDbType.VarChar);
PeriodFrom.Value = Program.form.TextBoxValue;
I tried to give you one of the ways to get the value but I do not think this is a good practice. Ideally, for passing values between forms, or layers you need to have some mechanism for storing and retrieving values, like a context, or Session. This is not the solution but a work around. And I take no responsibility if the code gets messed up cause of the above changes. :)

If your TextBox is publicly declared on your form, then you will be able to access its properties from the scope with which it was created in.
PeriodFrom.Value = otherForm.TextBoxName.Text;
If the 'previous' form object is not available to you now, then you will have to retrieve the value and pass it in as a parameter into your new form (or something of the sorts). Please supply more code/details if you want help here.

Change your textbox's modifier property to Public
then
formname.textboxname.Text

<%# PreviousPageType VirtualPath="~/SourcePage.aspx" %>
if(PreviousPage != null)
{
if(PreviousPage.IsCrossPagePostBack == true)
{
PeriodFrom.Value =PrevForm.TextBox.Text;
}
}
else
{
PeriodFrom.Value = "Not a cross-page post.";
}

YourPreviousForm.YourTextBox.Text

Get the value of textbox by using Text property of TextBox.
PeriodFrom.Value =PrevForm.TextBox.Text;
As you are saying that there is no accessbile due to protection level, you need to work on the access modifier of form from protected to public so that it can be accessible.

Related

Proper instatiating a WinForm via string in C#

I am working on a Winforms application that uses base window (e.g. Form1) and many other windows (e.g. Form2, Form3, ...). All of these windows have their property TopLevel set to false, no border and I am placing them in the Form1 when I need them. I am not skilled enough or do not have the brain capacity to solve this issue:
public void ShowForm(string strNewForm) {
var frmNew = Activator.CreateInstance(Type.GetType(strNewForm)) as Form;
frmNew.TopLevel = false;
frmNew.Size = new Size(rctForm.Width, rctForm.Height);
frmNew.Location = new Point(rctForm.X, rctForm.Y);
frmNew.InitializeForm(strActualSection, strActualSubSection);
frmNew.Parent = this;
frmNew.Show();
}
The strNewForm variable contains the name of Form to show. All the methods and properties in each Form can be used as these all are inherited from base class Form. Problem is with InitializeForm() which I use in each form (Form2, Form3, ...) to do various stuff. I know my problem is in this line:
var frmNew = Activator.CreateInstance(Type.GetType(strNewForm)) as Form;
When strNewForm contains string "Form2" and I change as Form to as Form2 it works just fine. I know I need to change it to proper name each time, but I don't know how. I tried to use this:
Type frmType = Type.GetType(strNewForm);
var frmNew = Activator.CreateInstance(Type.GetType(strNewForm)) as frmType;
But it throws an error CS0118: frmType is a variable but is used as a type. I don't know how to solve this, I tried many solutions and I googled for half a day straight and I am still lost. Any insight would be really helpful.
You cannot use a run-time variable to create strongly-typed code.
You have to provide a compile-time type after the as.
If you know it's a Form then all you can do is this:
var frmNew = Activator.CreateInstance(Type.GetType(strNewForm)) as Form;
If you need specific methods or properties then use a custom Form as your base-type and use that in the as.
Why won't you pass a Form object in your ShowForm method?
public void ShowForm(Form newForm)
{
newForm.TopLevel = false;
newForm.Size = new Size(rctForm.Width, rctForm.Height);
newForm.Location = new Point(rctForm.X, rctForm.Y);
newForm.InitializeForm(strActualSection, strActualSubSection);
newForm.Parent = this;
newForm.ShowDialog();
}

Connecting variables to another class

So I have a small project I am working on. Basically what I want to do is create another class, with the SQL connection as well as the results. However, it is telling me:
The Name 'firstName' does not exist.
When I put it on the page that is created for the designer mode in visual studio, it goes away and works.
info.cs:
public void GetInfo(string accountNumber)
{
string source = helper.CnnVal("WorkflowConfiguration");
SqlConnection con = new SqlConnection(source);
con.Open();
string sqlSelectQuery = $"Select TOP 1 * From [Workflow Creation].[dbo].[ssFields] Where Field16 =" + int.Parse(accountNumber);
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
firstName.Text = (dr["Field1"].ToString());
lastName.Text = (dr["Field2"].ToString());
dateOfbirth.Text = (dr["Field3"].ToString());
socialSecurity.Text = (dr["Field4"].ToString());
}
con.Close();
}
I would like to make a reference to the "designer" code page. So I can reference the results in the btn click below:
namespace WindowsFormsApp1
{
public partial class dataBase : Form
{
List<Information> people = new List<Information>();
private personalInfo personal = new personalInfo();
public dataBase()
{
InitializeComponent();
}
public void searchBtn_Click(object sender, EventArgs e)
{
dataAccess db = new dataAccess();
people = db.GetPeople(accountNumber.Text);
ListBoxPeople.DataSource = people;
ListBoxPeople.DisplayMember = "FullInfo";
//Would like to references here from info.cs
}
You seem to be dealing with Windows Forms here, as your main class is a Form. To start things off, I would like to recommend against giving Forms names that are completely unrelated to them. I have the habit of naming the main forms of my applications MainForm, but you could also use, for example, MyAppForm (the name of your application plus the word Form).
Setting that aside, if you need to access a control on your form (such as a TextBox), I recommend that you do so within the Form class itself, unless you have an excellent reason to do so. You will not be able to reference things from outside the form class (as controls are Private), and even if you write a method to pull the controls from your Form, you won't be able to access them (they will be on a different thread), unless you implement an algorithm to get around that.
Therefore, I suggest that you move your GetInfo method to your form class. Notice that that class is a partial class, that means you can create a new class file with the same class name and it will extend your form class, better organizing things (this is what Designer code generation does, hence why you're not supposed to alter things on the Designer file).
Edit: Additionally, as suggested above, if the context of your form doesn't suit your method, you can also pass the data required by a control via an extra public acessible method. That extra method can be called by your Form event, for example.
Note: Be sure to define the class as partial on the other file as well, if you intend to do this.

Accessing components of another form

I have two Forms in my application. A Form has the following fields: txtPower, txtTension and txtCurrent. I would like to access the values ​​filled in these TextBox through another Form. In the second Form I instantiated an object of the first Form (MotorForm), however I do not have access to the TextBox.
public MacroForm()
{
InitializeComponent();
MotorForm motorForm = new MotorForm();
motorForm.Show();
}
Is there any way?
Please do not expose the controls in your form. Never. (Unless you have a really good reason.)
If the problem is simple enough not to use MVVM (or the like) in your program (which you should consider for every program that's but trivial), you should expose the values of the instantiated form via properties. Think
public string Power
{
get { return txtPower.Text; }
set
{
if(ValidatePower(value))
{
txtPower.Text = value;
}
else
{
// throw ??
}
}
}
If we can make a sensible assumption about the type of the value we could extend this to
public double Power
{
get
{
// parse the value
// validate the value
// throw if not valid ??
// return the value
}
set
{
// validate the value
// set the value in the text box
}
}
If you exposed the txtPower object, you'd make the instantiating class depend on implementation details of the instantiated class, which is virtually never a good thing.
It seems that your problem is a perfect situation for using ShowDialog for opening your form.
To accomplish this, you need to change the Modifiers property of the controls you want to access on MotorForm and set them to Public. And also set the DialogResult property of your form somewhere to a desired value i.e OK. Anyway the easier way to do this is to set it on the button that is supposed to close the form. Suppose OK or CANCEL buttons.
Then you can create your form this way:
MotorForm motorForm = new MotorForm();
if(motorForm.ShowDialog() == DialogResult.OK)
{
string myValue = motorForm.txtPower.Text; //you can access your values this way
}

create hidden textbox, change it value in javascript and get new value. c#

I'm create a web custom control with hidden field:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
hidden = new HtmlInputHidden();
hidden.ClientIDMode = System.Web.UI.ClientIDMode.Static;
hidden.ID = this.ID + "_hidden";
this.Controls.Add(hidden);
}
I change it value in javascript on the page:
$(textbox).text("some text");
Then try to get this value:
string str = Request.Form[hidden.Name];
I get a null.... Also I tryed:
string str = Request.Form[hidden.ClientID]
and still get null.
Thanks.
So when accessing it from JavaScript you need to use this syntax:
$('#field_hidden').val("some text");
further, with the edit, I just noticed that you're not giving it a name as karaxuna stated. And finally, you'd need to make sure it's inside the form tag for it to be part of the Request.Form.
One other way of accessing its value though, even if it's built dynamically inside the Load, is to grab its value with the Value property. However, make sure you do that after the Load, in something like PreRender, because ASP.NET needs to have a chance to bind its value with ViewState.
Give it a name if you want to get it with Request.Form

Populating a form’s textbox with data from a second form

The application has two forms. The main form (Form#1) utilizes threading. One of these threads is used for reading in parameters from a TCP/IP socket. Once the value of one specific parameter has changed, I want to display this new value in a textbox on the second form (Form#2).
I have listed what I believe to be the significant parts of the code below.
Form#1:
//Resetting the manually adjusted 'gusBundlesPlacedOnPallet' parameter
if (gusBundlesInRow > 0)
{
gusBundlesInRow = 0;
//Update the 'BundlesOnPallet' display on the 'Manual Page' frmManualMode ManualMode = new frmManualMode();
ManualMode.NoOfBundlesInPalletizerDisplay(Convert.ToString(iIncomingMsg[15]));
}//End-if
Form#2:
//Creating a NoOfBundlesInPalletizer Delegate
public delegate void NoOfBundlesInPalletizerDisplayDelegate(string sMessage);
public void NoOfBundlesInPalletizerDisplay(string sMessage)
{
if (txtBundlesInPalletizer.InvokeRequired)
{
Invoke(newNoOfBundlesInPalletizerDisplayDelegate(NoOfBundlesInPalletizerDisplay), new object[] { sMessage });
}//End-if
else
{
this.txtBundlesInPalletizer.Text = sMessage;
}//End else-if
}//End method NoOfBundlesToPalletizeDisplay
The textbox on Form#2 will not show the new value, although if I insert a break point just after I have assign the new value to the textbox (sMessage), it does contain the correct value.
Additionally, if I close the second form and then reopen it, it will show the correct value. It looks to me that I need some kind of “refresh” of the textbox value?
Can anyone tell me what I’m doing wrong?
Thanks in advance
Terje
In my experience Control elements are always automatically updated. But you could try Control.Refresh();

Categories

Resources