Sharing data across forms with C# [duplicate] - c#

This question already has answers here:
C# - Winforms - Global Variables
(8 answers)
Closed 9 years ago.
I have been trying, without success, to share a variable between multiple forms. I am very new to c# and so have been failing miserably despite reading a couple of things about it.. Below is the programs code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Common;
using System.Data.OleDb;
namespace login
{
public partial class LoginScreen : Form
{
public LoginScreen()
{
InitializeComponent();
}
// Variables
int count = 0;
public static System.Data.OleDb.OleDbConnection con =
new System.Data.OleDb.OleDbConnection();//database connection
string dbProvider;
string dbSource;
OleDbDataAdapter da; // create database adapter 'da'
// CREATE DATASET VARIABLE ds1 TO HOLD THE DATABASE
public static DataSet ds1 = new DataSet();
string accountNo;
string sql;
string password;
int rownum = 0;
bool valid = false;
private void btnLogin_Click(object sender, EventArgs e)
{
accountNo = txtBoxAccntNo.Text;
valid = validate(); //uses validate() method to check validity
if (valid == true && accountNo == "11111111")
{
ManagerScreen Manager = new ManagerScreen();
this.Hide();
Manager.Show();
}
else if (valid == true)
{
s customer = new s();
this.Hide();
customer.Show();
}
else
{
if (count == 2)
{
this.Close();
}
count += 1;
txtBoxAccntNo.Clear();
txtBoxPinNo.Clear();
}
}
private void txtBoxAccntNo_TextChanged(object sender, EventArgs e)
{
}
private void LoginScreen_Load(object sender, EventArgs e)
{
// open database connection and load contents
// database connection
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"; // this is the database provider
dbSource = "Data Source = 'C:\\Bank.accdb'"; // navigation path
con.ConnectionString = dbProvider + dbSource;
}
private void btnExit_Click(object sender, EventArgs e)
{
// If button exit selected hide this form and open the welcome screen
WelcomeForm Welcome = new WelcomeForm();
this.Hide();
Welcome.Show();
}
// IsValid method checks that pass and login are valid
private bool validate()
{
ds1 = new DataSet();
con.Open();
// Validate Account number
sql = "SELECT * FROM tblCustomers WHERE ((tblCustomers.AccountNo) = '" + txtBoxAccntNo.Text + "')";
da = new OleDbDataAdapter(sql, con);
rownum = da.Fill(ds1, "tblCustomers");
con.Close();
if (rownum != 1)
{
MessageBox.Show("Not a valid Account number! - Try Again ");
return false;
}
else
{
// validate the pin
password = ds1.Tables["tblCustomers"].Rows[0][4].ToString();
if (password == txtBoxPinNo.Text)
{
MessageBox.Show("valid");
return true;
}
else
{
MessageBox.Show("Not a valid password - please try again ");
return false;
}
}
}
}
}
I want to share the variable accountNo with all other forms. Please advise, as I really need to get on with this. Thank you for any help.

You can make that accountNo property as static or either you can have some getter method to access that too.
If you set accountNo as static you can access it by just calling
ClassName.PropertyName
in your case
LoginScreen.accountNo will be the account number property.
Simple code sample
public partial class LoginScreen : Form
{
public LoginScreen()
{
InitializeComponent();
}
public static string accountNo;
}
public class AnotherClass
{
string accountNo = LoginScreen.accountNo;
}

The right way to go about this is to use the form to retrieve the information and then store it somewhere else to be accessed as you need it. Don't access it directly in the form from elsewhere - this will require you to keep the login form in scope for the whole application lifecycle. This probably isn't what you want.
In practice, this means creating something like a Global static class that everything has access to:
public static class Globals {
public static string AccountNumber {
get;
set;
}
}
From in your login form, after validating the login as correct, you would simply do:
Globals.AccountNumber = txtBoxAcctNo.Text;
Then, anywhere else you need the AccountNumber, you can access it as Globals.AccountNumber.

I can recommend one of three ways to achieve what you want:
Make accountNo a public static variable. Then, other forms can access it by LoginScreen.accountNo (it's better to have a property to control visibility). This is a good approach if you might have many active instances of LoginScreen and they all might update accountNo and you want any form which accesses this field to get the latest value.
Implement a singleton pattern for the entire form and have accountNo in it as a public variable. This is a good approach if you will only have one instance of the firm active at any time.
Have accountNo be static member in another class and have LoginScreen access it by UtilClass.accountNo. This is a good approach if other forms/classes might want to update the field and/or it's a field which shouldn't be associated with this form.

Related

Accessing RowCount from another class

I have a winform, that takes a number of params, executes an stored procedure and then populates a DataGridView with the results.
What I'd like to do is add a string the bottom of my winform that returns a message, including a count of total rows returned.
This presently works fine, using the following syntax :
deskSearchResultCount.Text = String.Format("Your search returned {0} results", deskDataGridView.RowCount );
However as the majority of my application has been written out in the initial form, I was moving sections into classes, to 'tidy it up' a bit - (I'm still very new to c# so apologies if this is a n00b mistake)
Once I add a class called Summary, I would like to call my RowCount as follows :
Summary Returned = new Summary();
deskSearchResultCount.Text = String.Format("Your search returned {0} results", Returned.Total("Desk"));
With my Summary class containing the following :
public class Summary : ContactAnalysisToolbox
{
public int Total(string type)
{
if (type == "Desk")
{
return deskDataGridView.Rows.Count;
}
else
{
return visionDataGridView.Rows.Count;
}
}
However the returned count is always 0. When stepping through the process also, at no point does it appear to be attempting to set itself as anything different.
Can anyone please help / point me in the right direction?
Thanks.
Edit -
I've included the full form also -
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.DirectoryServices.AccountManagement;
using System.IO;
//
// Todo :
// -- Capture Assigned Team In Output
//
//
namespace CallsAnalysisToolbox
{
public partial class ContactAnalysisToolbox : Form
{
public ContactAnalysisToolbox()
{
InitializeComponent();
// Grabs username for current user and displays a welcome message
this.welcomeMessage.Text = "Welcome " + UserPrincipal.Current.Name;
}
private void searchVision_Click(object sender, EventArgs e)
{
try
{
// Run sp_incomingCalls on SQLCLUSTER
this.rep_IncomingCallsTableAdapter.Fill(this.visionReportsDataSet.Rep_IncomingCalls, dateTimePicker1.Value, dateTimePicker2.Value, textBox1.Text, textBox2.Text);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
// Make export button active when search returns results
exportVisionButton.Enabled = (visionDataGridView.Rows.Count > 0);
// Assign returned row count to visionSearchResultCount label and then display label
visionSearchResultCount.Text = String.Format("Your search returned {0} results", visionDataGridView.RowCount);
visionSearchResultCount.Visible = true;
}
private void searchDesk_Click(object sender, EventArgs e)
{
try
{
// Run sp_caseActivity on SQLCLUSTER
this.rPT_CaseActivityTableAdapter.Fill(this.deskDataSet.RPT_CaseActivity, deskFrom.Value, deskTo.Value, deskClientList.Text, deskBenefitList.Text, deskStatusList.Text);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
if (deskDataGridView.Rows.Count > 0)
{
exportDeskButton.Enabled = true;
deskSearchResultCount.Visible = true;
Summary Returned = new Summary();
deskSearchResultCount.Text = String.Format("Your search returned {0} results", Returned.Total("Desk"));
deskSummaryData.Visible = true;
noDataDesk.Visible = false;
// Populate the summary tab
// Get Email / Phone case count
deskTotalCaseResults.Text = deskDataGridView.RowCount.ToString();
//deskTotalEmailCasesResults.Text = emailCount.ToString();
//deskTotalPhoneCasesResults.Text = phoneCount.ToString();
}
}
//TODO : Combine Export functions. Ideally just a single function rather than the repeated logic within the Export class for each datagrid
private void exportVisionButton_Click(object sender, EventArgs e)
{
Export Export = new Export();
Export.ReturnedResult("Vision");
}
private void exportDeskButton_Click(object sender, EventArgs e)
{
Export Export = new Export();
Export.ReturnedResult("Desk");
}
private void deskDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
// Limit 'open case in browser' action to first cell
if (deskDataGridView.CurrentCell.ColumnIndex.Equals(0))
{
string url = string.Format("https://qa.internal.local/agent/case/{0}", deskDataGridView.Rows[e.RowIndex].Cells[0].Value);
Process.Start(url);
}
}
}
}
For example you could do something like this. It's called Method Extension
Try this
public static class Helpers
{
public static string ToTotalCount(this DataGridView item)
{
return string.Format("Your search returned {0} results", item.Rows.Count);
}
}
In your form make sure that the namespace of the class Helpers is in the usings:
deskSearchResultCount.Text = deskDataGridView.ToTotalCount();

C# view data in form linked with foreign key

I have a local database (SQL) with two tables Contact and Address. The Contact table contains 5 address fields (Address1, Address2,...) that are foreign keys linked to the primary key of the Address table. What ik want to do is when I select (for instance using a combobox) a contacts name, view all addresses linked to the contact. I'm a complete noob in C# programming and have no idee to make the above happen. Can anyone show me how I can view the addresses by selecting the contacts name?
EDIT (after trying some coding):
Ok, this is how far I get. I have my two forms. FORM 1 has a datagridview, viewing a button, firstname and lastname. Entering firstname and lastname in textBox1 and textBox2 and pressing button1 results in a list of records that match firstname OR lastname.
Clicking the button in column 0 shows the contactsheet. I've tried to pass firstname and lastname to textboxes tboFNAME and tboLNAME, but nothing appears in these textboxes.
In the next stage I would like to pass the address ID's (foreign keys) to the contactsheet and subsequently load the linked data in the corresponding textboxes.
FORM 1:
public partial class Form1 : Form
{
//SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\xxx\Documents\Visual Studio 2013\Projects\xxx\xxx\xxx.mdf;Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\xxx\Documents\Visual Studio 2013\Projects\xxx\xxx\xxx.mdf;Integrated Security=True;Connect Timeout=30");
dataGridView1.Visible = true;
int varCount;
varCount = 0;
int i = 0;
for (i = 1 ; i < dataGridView1.Rows.Count-1; i++)
{
if (!dataGridView1.Rows[i].IsNewRow)
{
if (dataGridView1[3, i].Value.ToString() == textBox1.Text
|| dataGridView1[5, i].Value.ToString() == textBox2.Text
)
{
dataGridView1.Rows[i].Visible = true;
varCount += 1;
Console.WriteLine(varCount);
int RHeight = dataGridView1.RowTemplate.Height;
int gridHeight = (varCount * RHeight) + RHeight;
dataGridView1.Height = gridHeight;
}
else
{
dataGridView1.Rows[i].Visible = false;
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'sAFIREDBDataSet1.contactdata' table. You can move, or remove it, as needed.
this.contactdataTableAdapter1.Fill(this.sAFIREDBDataSet1.contactdata);
this.contactdataTableAdapter.Fill(this.sAFIREDBDataSet.contactdata);
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
String fnameRef = (String)dataGridView1.Rows[e.RowIndex].Cells[3].Value;
String lnameRef = (String)dataGridView1.Rows[e.RowIndex].Cells[5].Value;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
e.RowIndex >= 0)
{
Contactsheet myForm = new Contactsheet();
myForm.getFNAME = fnameRef;
myForm.getLNAME = lnameRef;
myForm.Show();
}
}
}
FORM 2 (Contactsheet)
public partial class Contactsheet : Form
{
public Contactsheet()
{
InitializeComponent();
}
public string getFNAME;
public string getLNAME;
private void Contactsheet_Load(object sender, EventArgs e)
{
tboFNAME.Text = getFNAME;
tboLNAME.Text = getLNAME;
}
}
First of all you must connect to your SQL db as you probably know.
I think that the simplest way will be to use Entity Framework (version 5 or 6).
Create new edmx file, new connection to your database and import your tables.
Try to write some code. May be you figured it out. If not then ask more accurate question with examples of your tries:)

Calling an SQL stored procedure that's defined in a method using button click on form c#

Having a lot of trouble with this. I'm working on a large project, so there's only a few classes I'm interested in and working on. Basically, these are forms - one is a main editor where a user edits details and the other is used to assign a pin number. In the main editor form, if the user has a pin, they can choose to edit this pin. Here's where my problem lies - if I edit the pin, what I'm doing in the code is deleting the old pin and adding the new one. However, the database doesn't update until AFTER the editor form is closed. Therefore, I'd like to call the method that does change the database on the OKButton click, if I could. The problem I'm facing is I don't know how.
Here is the DB code, we'll say the class is called DetailsConn:
public string editPin(int driverID)
{
if (SchemaChecker.PINAvailable())
{
string sql = "EditPIN";
using (SqlCommand cmd = new SqlCommand(sql, base.connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Remove("#nDriverID");
cmd.Parameters.AddWithValue("#nDriverID", driverID);
cmd.Parameters.Remove("#nPIN");
SqlParameter pinParameter = cmd.Parameters.Add("#nPIN", SqlDbType.Char);
pinParameter.Direction = ParameterDirection.Output;
pinParameter.Size = 32;
cmd.ExecuteNonQuery();
return pinParameter.Value.ToString();
}
}
return "";
}
Here's the code for my edit:
private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.listViewDriverTags.SelectedItems.Count > 0)
{
ListViewItem lvi = this.listViewDriverTags.SelectedItems[0];
DriverTag driverTag = lvi.Tag as DriverTag;
else if (blahTag.blahType == 2)
{
buttonAssignPIN_Click(sender, e);
}
//message stuff and dialog boxes with localization info
if (dr == DialogResult.Yes)
{
this.listViewDriverTags.Items.Remove(lvi);
if (Tag.id != -1)
{
TagsToBeDeleted.Add(driverTag);
}
}
if (dr == DialogResult.No)
{
this.listViewTags.Items.Clear();
this.listViewTags.Items.Add(lvi);
}
}
}
Here's my buttonAssignPIN stuff:
private void buttonAssignPIN_Click(object sender, EventArgs e)
{
using (AssignPINForm form = new AssignPINForm())
{
if (form.ShowDialog(this) == DialogResult.OK)
{
DriverTag PIN = DriverTag.GetNewPIN(form.DriverTag);
ListViewItem lvi = this.listViewTags.Items.Add(PIN.driverTag);
lvi.SubItems.Add(this.TagTypes[PIN.TagType]);
lvi.Tag = PIN;
}
}
}
And finally, here's my AssignPINForm code:
public partial class AssignPINForm : Form
{
public AssignPINForm()
{
InitializeComponent();
this.buttonOK.Click += new EventHandler(buttonOK_Click);
this.buttonCancel.Click += new EventHandler(buttonCancel_Click);
this.buttonOK.Enabled = false;
this.textBoxPin.TextChanged += delegate(object sender, EventArgs e)
{
String pattern = #"^[0-9]{4,20}$";
Regex regex = new Regex(pattern);
buttonOK.Enabled = regex.IsMatch(textBoxPin.Text);
};
LoadStrings();
}
public void LoadStrings()
{
//stome stuff
}
public string DriverTag
{
get { return this.textBoxPin.Text; }
set { this.textBoxPin.Text = value; }
}
private void buttonOK_Click(object sender, EventArgs e)
{
}
private void buttonCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void AssignPINForm_Load(object sender, EventArgs e)
{
}
}
I know it's kind of all over the place but I've provided everything I think is relevant. The middle two snippets are in the same class too, and the DB stuff is the same solution but a different project. I'd be grateful if someone can decipher what I'm after and help me out, it's the only thing I have left to do on this particular bit!
Thanks!
Not sure I fully got what you're after and I agree with some of the comments that this isn't the best of practice but I guess what you're after is to update the buttonOK_Click method to something like this:
private void buttonOK_Click(object sender, EventArgs e)
{
using(DetailsConn connection = new DetailsConn())
{
int driver = -1;
if(int.TryParse(this.DriverTag, out driver)) {
connection.editPin(driver);
}
}
}
Also, you may want to remove any other possible references to the editPin() function.
I actually figured out that even if I got that working correctly, it wasn't going to solve my problem. I've had to call a new procedure and declare that in the database schema - basically it was a lot more complicated than what I was giving it credit for. Thanks for the responses nonetheless.

public variables using in the second form

I have a "simple" problem with assign variables from FORM1 (in my code Form1) and using those variables in FORM2 (in my code frLeczenie). So I started to create a public string variables:
public string wynikImie;
public string wynikUmaszczenie;
public string wynikDataUrodzenia;
public string wynikPlec;
public string wynikZnakiSzczegolne;
public string wynikCzyWykastrowane;
To those variables I'll assign data from SQL Database:
private void dgZwierze_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
string zapytanie = "SELECT IMIE_ZWIERZECIA, DATA_URODZENIA, PLEC, ZNAKI_SZCZEGOLNE, UMASZCZENIE, CZY_WYKASTROWANE FROM tbZwierze WHERE tbZwierze.IMIE_ZWIERZECIA = '" + wynikImie + "' AND tbZwierze.UMASZCZENIE = '" + wynikUmaszczenie + "'";
SqlCommand cmdZapytanie = new SqlCommand(zapytanie, cs);
cs.Open();
SqlDataReader reader = cmdZapytanie.ExecuteReader();
if (reader.Read())
{
wynikImie = reader.GetValue(0).ToString();
wynikDataUrodzenia = reader.GetValue(1).ToString();
wynikPlec = reader.GetValue(2).ToString();
wynikZnakiSzczegolne = reader.GetValue(3).ToString();
wynikUmaszczenie = reader.GetValue(4).ToString();
wynikCzyWykastrowane = reader.GetValue(5).ToString();
}
cs.Close();
}
To this moment all is great, but problem occurs when I opened the FORM2:
private void btnLeczenie_Click(object sender, EventArgs e)
{
frLeczenie leczenie = new frLeczenie();
leczenie.ShowDialog();
}
Suddenly my all data assigned to public string variables is missing, and I can't using their in the FORM 2:
private void frLeczenie_Load(object sender, EventArgs e)
{
Form1 formaglowna = new Form1();
textBox1.Text = formaglowna.wynikImie;
textBox2.Text = formaglowna.wynikDataUrodzenia;
textBox3.Text = formaglowna.wynikPlec;
textBox4.Text = formaglowna.wynikZnakiSzczegolne;
textBox5.Text = formaglowna.wynikUmaszczenie;
textBox6.Text = formaglowna.wynikCzyWykastrowane;
}
What I'm doing wrong? Maybe I missing something? Could you take a look on this?
Regards,
Peter.
new Form1(); creates a new instance of your first form, but you want to use the already initialized form with it's variables instead. So you could pass the form instance via constructor to your second form and store it in a property:
in first form:
frLeczenie leczenie = new frLeczenie(this);
second form constructor:
public frLeczenie(Form1 formaglowna)
{
InitializeComponent();
this.Formaglowna = formaglowna;
// ...
}
public Form1 Formaglowna{ get; set; }
Now you access them via property:
textBox1.Text = Formaglowna.wynikImie;
// ...
Note that you set the values in an instance of the form in it's dgZwierze_CellContentClick method. However in form 2 you are creating a new Form1 that has never been shown or had that method called. So the values are empty.
Form1 formaglowna = new Form1();
textBox1.Text = formaglowna.wynikImie;
What you need is to pass the real form1 into form2 and not create a new form 1
When you create the new form1 in the last part of your code, it is a new blank instance of the class. Each instance of a class or form will have its own variable values. If you really need these variables to be available and shared on all objects of a given class, make them static.

Databound DateTimePicker Time in C#

I'm have a Windows Form with 2 datetimepicker controls: one for date and a separate datetimepicker control for time. Both of these controls are bound to the same column in a database and the controls have different property names (i.e., dateEdit and timeEdit) and different formats (i.e., Long and Time).
Here are my problems/questions:
The timeEdit picker ignores whatever seconds are in the database entry and sets the time seconds to "00", as in "2:34:00", even though the database entry (trimmed to time for this illustration) is "14:34:31.891123 -04:00". How can I get the seconds to correctly display?
Whenever I edit the seconds in the timeEdit picker from "00" to (for example) "15", as in "2:34:15", the picker resets the seconds to "00" before passing the value to the next function. How do I pass the correct seconds value?
I'd like to edit the milliseconds on the time. Is it best for me to bind the trimmed milliseconds (using DATEPART) to a text box? Will I need to convert or cast the milliseconds to a char or string in order to correctly display them in a text box?
Thanks for any help!
Code to trigger the edit form:
private void timeDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.ColumnIndex == 5)
{
EditTime editForm = new EditTime((Guid)timeDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
editForm.StartPosition = FormStartPosition.CenterScreen;
editForm.ShowDialog();
editForm.Close();
}
}
catch (Exception ex)
{
string msg = "Error: ";
msg += ex.Message;
throw new Exception(msg);
}
}
Code for the form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace StatusManager
{
public partial class EditTime : Form
{
private Guid calendarId;
public EditTime()
{
InitializeComponent();
}
public EditTime(Guid Id)
{
InitializeComponent();
calendarId = Id;
}
public string GetConnectionString()
{
var connString = ConfigurationManager.ConnectionStrings["StatusManager.Properties.Settings.StatusConnectionString"].ConnectionString;
return connString;
}
private void UpdateCalendarItem(string dateEdit, string timeEdit, string note)
{
var conn = new SqlConnection(GetConnectionString());
const string UpdateStatusSql = #"UPDATE dbo.statuses SET
calendarTime = #timeOffset
notes = #note
WHERE PK_calendarUID = #PK_calendarUID";
try
{
SqlCommand cmd = new SqlCommand(UpdateSql, conn);
var param = new SqlParameter[3];
param[0] = new SqlParameter("#PK_calendarUID", calendarId);
//Convert date(s) to correct format
string dateTimeCombined = dateEdit + " " timeEdit;
DateTime timeConverted = Convert.ToDateTime(dateTimeCombined);
DateTimeOffset timeOffset = new DateTimeOffset(timeConverted);
param[1] = new SqlParameter("#timeOffset", timeOffset);
param[2] = new SqlParameter("#note", note);
foreach (SqlParameter t in param)
{
cmd.Parameters.Add(t);
}
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string msg = "Error updating 'calendarItems': ";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
private void editTimeButton_Click(object sender, EventArgs e)
{
UpdateCalendarItem(dateEdit.Text, timeEdit.Text, notes.Text);
this.Close();
}
private void EditTime_Load(object sender, EventArgs e)
{
this.locationsTableAdapter.Fill(this.locationsDataSet.locations);
this.calendarTableAdapter.FillById(this.calendarDataSet.calendarItems, calendarId);
}
}
}
Code for instantiating the datetimepicker:
this.timeEdit.CustomFormat = "";
this.timeEdit.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.calendarBindingSource, "calendarTime", true));
this.timeEdit.Format = System.Windows.Forms.DateTimePickerFormat.Time;
this.timeEdit.Location = new System.Drawing.Point(385, 30);
this.timeEdit.Name = "timeEdit";
this.timeEdit.ShowUpDown = true;
this.timeEdit.Size = new System.Drawing.Size(89, 20);
this.timeEdit.TabIndex = 2;
You need to use DateTimePicker.CustomFormat Property
s The one- or two-digit seconds.
ss The two-digit seconds. Single digit values are preceded by a 0.
You can't use DateTimePicker for milliseconds.
Problem solved but I'm not exactly sure how. Here's what I did:
In calendarDataSet, I updated both queries (Fill,GetData and FillById,GetDataBy (#ID)) to select calendarTime as CONVERT(VARCHAR(12), calendarTime, 114) AS calHoursMinsSec
In essence, I created created a new column with the hours, minutes, seconds, and milliseconds
On the form, I added a textbox and bound the textbox to calHoursMinsSec
Note: My previous attempts to convert the datetime to a varchar to were unsuccessful no doubt due to operator error.
Once I saved the form, the binding seemed to stick and I was able to pass the relevant variables to the update function
Thanks for everyone's input! I appreciate the guidance and suggestions!

Categories