Copy text from row in GridEX - c#

Using Janus GridEx control, Visual C#. I have a timer that updates the grid every 3 min through a stored function on the DB. How can I double click a specific row and have it show within a multiple line textbox with the text of the 4 cells in the grid?
Been at this for 4 days and am going NUTS!!!
Starting form:
public DSC_Mon()
{
InitializeComponent();
Caller = new DSCU_SvcConsumer.MTCaller();
dsZA = new DataSet();
dsOut = new DataSet();
this.gridEXMon.DoubleClick += new System.EventHandler(this.gridEXMon_DoubleClick);
}
private void DSC_Mon_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void LoadData()
{
if (!dsZA.Tables.Contains("Query"))
{
DataTable dtZA = dsZA.Tables.Add("Query");
dtZA.Columns.Add("str");
dtZA.Rows.Add(string.Format(#"exec MON_GetStatus"));
}
//dtZA.Rows.Add(string.Format(#"select * from am_company"));
dsOut.Clear();
dsOut.Merge(Caller.CallRequest("ZuluAction", dsZA));
if (gridEXMon.DataSource == null)
{
gridEXMon.DataSource = dsOut;
gridEXMon.DataMember = "Table";
}
//gridEXMon.RetrieveStructure();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
LoadData();
timer1.Enabled = true;
}
private void gridEXMon_DoubleClick(object sender, EventArgs e)
{
ReportInfo report = new ReportInfo();
report.ShowDialog();
}
}
}
Popup Box:
public ReportInfo()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string value = "System: " + Environment.NewLine + systemNameTextBox.Text + Environment.NewLine +
Environment.NewLine + "Manager: " + Environment.NewLine + contactName1TextBox.Text +
Environment.NewLine + Environment.NewLine + "Function Name: " + Environment.NewLine +
functionNameTextBox.Text;
Clipboard.SetText(value);
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpaddress");
mail.From = new MailAddress("emailaddress");
mail.To.Add("emailaddress");
mail.Subject = "Test Mail";
mail.Body = value;
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = false;
SmtpServer.Send(mail);
MessageBox.Show(" Report Information sent to Service Support Group");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

You need to use the RowDoubeClick event of the GridEX.
This is how to use it:
private void gridEXMon_RowDoubleClick(object sender, Janus.Windows.GridEX.RowActionEventArgs e)
{
if (e.Row.RowIndex < 0)
return;
int BillID = Convert.ToInt32(e.Row.Cells["Cell1"].Value);
String BillID = Convert.ToString(e.Row.Cells["Cell2"].Value);
Decimal BillID = Convert.ToDecimal(e.Row.Cells["Cell3"].Value);
int BillID = Convert.ToInt32(e.Row.Cells["Cell4"].Value);
ReportInfo report = new ReportInfo();
// Here you need to pass the 4 cell values to your Pop up Dialog
report.ShowDialog();
}

Related

TweetInvi Listview can't get TweetID

I'm trying to get Tweet ID via TweetInvi API but always get null point exception. I'm out of options and can't understand what i did wrong. Here is my code. Problem occurs when i select desired Item from view and press retweet.
namespace MIF_TwitterApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Auth.SetUserCredentials("KEY", "KEY", "KEY",
"KEY");
}
private void Form1_Load(object sender, EventArgs e)
{
var user = User.GetAuthenticatedUser();
//PROFILE
profileImage.ImageLocation = user.ProfileImageUrlFullSize;
nameLabel.Text = user.Name;
usernameLabel.Text = "#" + user.ScreenName;
followersLabel.Text = "Followers: " + user.FollowersCount;
}
//Tweeting with PICS
private void tweetBtn_Click(object sender, EventArgs e)
{
if (tweetBox.Text != "")
{
if (imgUploadPath.Text != "")
{
byte[] file = File.ReadAllBytes(imgPreview.ImageLocation);
Tweet.PublishTweetWithImage(tweetBox.Text, file);
imgPreview.ImageLocation = "";
imgUploadPath.Text = "";
tweetBox.Clear();
MessageBox.Show("Tweet posted!");
}
else
{
Tweet.PublishTweet(tweetBox.Text);
MessageBox.Show("Tweet posted!");
tweetBox.Clear();
}
}
else
{
MessageBox.Show("Please enter text!");
tweetBox.Clear();
}
}
private void addImg_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
imgPreview.ImageLocation = ofd.FileName;
imgUploadPath.Text = ofd.FileName;
}
private void dropImg_Click(object sender, EventArgs e)
{
imgPreview.ImageLocation = "";
imgUploadPath.Text = "";
}
private void timelineBtn_Click(object sender, EventArgs e)
{
var user = User.GetAuthenticatedUser();
var getTweets = Timeline.GetHomeTimeline(40);
listView1.Clear();
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
listView1.Columns.Add("Tweet", 570);
listView1.Columns.Add("Created By", 130);
listView1.Columns.Add("Create Time", 130);
listView1.Columns.Add("Likes", 60);
listView1.Columns.Add("Retweets", 70);
int x = 0;
foreach (var t in getTweets)
{
ListViewItem listItem = new ListViewItem(t.Text);
listItem.SubItems.Add(t.CreatedBy.ScreenName.ToString());
listItem.SubItems.Add(t.CreatedAt.ToString());
listItem.SubItems.Add(t.FavoriteCount.ToString());
listItem.SubItems.Add(t.RetweetCount.ToString());
listView1.Items.Add(listItem);
listView1.Items[x].Tag = t.Id;
}
}
private void postsBtn_Click(object sender, EventArgs e)
{
var user = User.GetAuthenticatedUser();
var getTweets = Timeline.GetUserTimeline(user, 40);
listView1.Clear();
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
listView1.Columns.Add("Tweet", 570);
listView1.Columns.Add("Created By", 130);
listView1.Columns.Add("Create Time", 130);
listView1.Columns.Add("Likes", 60);
listView1.Columns.Add("Retweets", 70);
int x = 0;
foreach (var t in getTweets)
{
ListViewItem listItem = new ListViewItem(t.Text);
listItem.SubItems.Add(t.CreatedBy.ScreenName.ToString());
listItem.SubItems.Add(t.CreatedAt.ToString());
listItem.SubItems.Add(t.FavoriteCount.ToString());
listItem.SubItems.Add(t.RetweetCount.ToString());
listView1.Items.Add(listItem);
listView1.Items[x].Tag = t.Id;
}
}
private void retweetBtn_Click(object sender, EventArgs e)
{
var checkedItems = listView1.SelectedItems;
long a = (long)listView1.SelectedItems[0].Tag;
var user = User.GetAuthenticatedUser();
var retweet = Tweet.PublishRetweet(a);
MessageBox.Show("Retweet was successfull");
listView1.Items.Clear();
}
}
}
Breakes on long a, I can't figure out how to get that Long Tweet ID
Here is the full code
Problem was that my X was not incrementing correctly as it was out of for loop.
int x = 0;
foreach (var t in getTweets)
{
ListViewItem listItem = new ListViewItem(t.Text);
listItem.SubItems.Add(t.CreatedBy.ScreenName.ToString());
listItem.SubItems.Add(t.CreatedAt.ToString());
listItem.SubItems.Add(t.FavoriteCount.ToString());
listItem.SubItems.Add(t.RetweetCount.ToString());
listView1.Items.Add(listItem);
listView1.Items[x].Tag = t.Id;
x = x +1;
}

Regarding strongly typed dataset in windows form application

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace GST.Masters
{
public partial class Customers : Heptanesia.Winforms.Ui.Forms.MainUC
{
public static string recCode
{ get; set; }
public string RC;
public bool insertFlag;
public Data.GSTDb.CustomersRow r;
public Data.GSTDb.CustomersGSTNosRow gr;
public Data.GSTDb.CustomersDataTable dt = new Data.GSTDb.CustomersDataTable();
public Customers()
{
InitializeComponent();
recCode = Guid.NewGuid().ToString();
this.Load += new EventHandler(this.Customers_Load);
this.Ts.SaveClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.SaveClickedEventHandler(this.Ts_SaveClicked);
this.Ts.AddNewClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.AddNewClickedEventHandler(this.Ts_AddNewClicked);
this.Ts.SearchClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.SearchClickedEventHandler(this.Ts_SearchClicked);
this.DgGST.CellValidated += (sender, e) =>
{
string name = this.DgGST.Columns[e.ColumnIndex].Name;
if (name == "DGCCountryCode")
{
name = this.DgGST.Rows[e.RowIndex].Cells[name].Value.ToString();
this.statesBindingSource.Filter = "ParentCode = '" + name + "'";
if (!this.FormIsLoading)
{
this.DgGST.Rows[e.RowIndex].Cells["DGCStateCode"].Value = null;
this.DgGST.Rows[e.RowIndex].Cells["DGCCityCode"].Value = null;
}
}
else if (name == "DGCStateCode")
{
name = this.DgGST.Rows[e.RowIndex].Cells[name].Value.ToString();
this.citiesBindingSource.Filter = "ParentCode = '" + name + "'";
if (!this.FormIsLoading)
{
this.DgGST.Rows[e.RowIndex].Cells["DGCCityCode"].Value = null;
}
}
};
}
private void Ts_AddNewClicked(object sender, EventArgs e)
{
this.gSTDb.Customers.Rows.Clear();
r = this.gSTDb.Customers.NewCustomersRow();
this.gSTDb.Customers.AddCustomersRow(r);
Data.GSTDbTableAdapters.CustomersGSTNosTableAdapter CGT = new Data.GSTDbTableAdapters.CustomersGSTNosTableAdapter();
CGT.FillByParentCode(gSTDb.CustomersGSTNos, r.RecCode);
}
private void Ts_SearchClicked(object sender, EventArgs e)
{
Heptanesia.Winforms.Ui.Forms.SearchForm sf = new Heptanesia.Winforms.Ui.Forms.SearchForm();
sf.DataSource = new Data.GSTDbTableAdapters.CustomersTableAdapter().GetData();
sf.DisplayColumns = new string[] { "Name" };
sf.DisplayHeaders = new string[] { "Customers Name" };
sf.DisplayWidths = new int[] { 200 };
if (sf.ShowDialog(this) == DialogResult.OK)
{
this.RC = sf.ReturnRow["RecCode"].ToString();
this.customersTableAdapter.FillByRecCode(this.gSTDb.Customers, RC);
}
}
private void Ts_SaveClicked(object sender, EventArgs e)
{
string message = "Error: ";
try
{
this.customersBindingSource.EndEdit();
//if (this.DgGST.CurrentRow.DataBoundItem != null)
this.fkCustomerGSTNosCustomersBindingSource.EndEdit();
if (this.gSTDb.Customers.HasErrors)
message += Classes.Global.SetBindingSourcePositionAndGetError(this.customersBindingSource, this.gSTDb.Customers.GetErrors()[0]);
else if (this.gSTDb.CustomersGSTNos.HasErrors)
message += Classes.Global.SetBindingSourcePositionAndGetError(this.fkCustomerGSTNosCustomersBindingSource, this.gSTDb.CustomersGSTNos.GetErrors()[0]);
else
{
this.gSTDb.Customers.BeforeSave();
this.gSTDb.CustomersGSTNos.BeforeSave();
Data.GSTDbTableAdapters.TableAdapterManager tm = new Data.GSTDbTableAdapters.TableAdapterManager();
tm.CustomersTableAdapter = this.customersTableAdapter;
tm.CustomersGSTNosTableAdapter = this.customersGSTNosTableAdapter;
tm.UpdateAll(this.gSTDb);
message = "Record(s) Saved Successfully";
}
}
catch (Exception ex)
{
message += ex.Message;
}
MessageBox.Show(message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void Customers_Load(object sender, EventArgs e)
{
this.FormIsLoading = true;
this.customersTableAdapter.Fill(this.gSTDb.Customers);
this.customersGSTNosTableAdapter.Fill(this.gSTDb.CustomersGSTNos);
this.countriesTableAdapter.Fill(this.gSTDb.Countries);
this.statesTableAdapter.Fill(this.gSTDb.States);
this.citiesTableAdapter.Fill(this.gSTDb.Cities);
this.gSTDb.Customers.Rows.Clear();
if (this.gSTDb.Customers.Rows.Count == 0)
{
Data.GSTDb.CustomersRow r = this.gSTDb.Customers.NewCustomersRow();
this.gSTDb.Customers.AddCustomersRow(r);
}
this.FormIsLoading = false;
}
private void DgGST_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
if (e.Exception is ArgumentException)
{
object value = DgGST.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (!((DataGridViewComboBoxColumn)DgGST.Columns[e.ColumnIndex]).Items.Contains(value))
{
((DataGridViewComboBoxCell)DgGST[e.ColumnIndex, e.RowIndex]).Value = DBNull.Value;
//((DataGridViewComboBoxColumn)dgv.Columns[e.ColumnIndex]).Items.Add(value);
e.ThrowException = false;
}
}
else
{
MessageBox.Show(e.Exception.Message);
e.Cancel = true;
}
}
}
}
I am developing one simple invoice application in which I am having a simple Customer screen module.A Customer can have any number of GST records in the Datagridview.The Screen is based on Customer Masters(Textboxes) and Customers Master Details(Datagridview) relationship through foreign keys. And I am Using Strongly Typed Dataset in this project as a xsd file.This Screen has 3 buttons i.e.New,Save and Find toolstrip menu.
When I start adding records after clicking on New Buttonstrip and and save ,it saves it successfully and when I press New Ideally it should clear the rows.The main issue here is that it is not clearing the rows??
I am enclosing the cs file here.
What I have tried:
Everything as I can Do.
Clearing the Rows through Rows.Clear(); 2) I tried clearing
Binding Source and DataGridview after setting it null.
Nothing Worked.

How can I save the path of an image in OpenFileDialog to a string?

I am currently working on a small DB project in which I have tried implementing a browser for image so that they can be saved for each player accordingly.
I am particularly struggling with wring the path of the image to a string, and the storing that string into the arraylist which will then be used to load the file by using the path stored in that arraylist. As you see in the code I have tried to assign the OpenFd.FileName to a string called pathToImage but it doesn't work, the string remains empty after a quick debug check using MessageBox.Show(pathToImage)
Can anyone help me?
using System;
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.IO;
using System.Collections;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;
namespace Assignment1_Template2
{
public partial class Form1 : Form
{
// =======================The data Structure ===========================
// ========Uses [SERIALIZABLE] to allow simple loading/saving ==========
[Serializable]
private struct myStruct
{ // The "constructor". Fills data structure with default values
public myStruct(int playerId)
{
uniquePlayerId = new int[playerId];
playerIgName = "";
contactStreet = "";
contactTown = "";
contactPostcode = "";
contactEmail = "";
contactTelephone = "";
imagePath = "";
for (int i = 0; i < playerId; ++i) uniquePlayerId[i] = 0;
}
// The data types of the struct
public int[] uniquePlayerId;
public string playerIgName;
public string contactStreet;
public string contactTown;
public string contactPostcode;
public string contactEmail;
public string contactTelephone;
public string imagePath;
}
// ================== End of data Structure definition ===================
// =======================================================================
// ================ Global Variables used in the Program =================
private ArrayList dataList; // This is the main data collection
private int currentEntryShown = 0; // current myStruct on display
private int numberOfEntries = 0; // total number of myStructs
private string filename = "C:\\test.dat"; // path of the file being read in
public string pathToImage = "";
public string pathToImagePlaceholder = "";
// =======================================================================
// ================== STARTING POINT FOR THE PROGRAM =====================
public Form1()
{
// Brings up the window.
InitializeComponent();
// Create the ArrayList
dataList = new ArrayList();
// Call methods implemented below
LoadData();
ShowData();
UpdatePrevNextBtnStatus();
}
// =========================================================================
// =================== END OF STARTING POINT FOR PROGRAM ===================
// ========= All further events are now triggered by user actions ==========
// =========================================================================
// =========================================================================
// ========================= BUTTON ACTION HANDLERS ========================
// =========================================================================
private void showPreviousBtn_Click(object sender, EventArgs e)
{
--currentEntryShown;
ShowData();
UpdatePrevNextBtnStatus();
}
private void showNextBtn_Click(object sender, EventArgs e)
{
++currentEntryShown;
if (currentEntryShown != dataList.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void addNewPlayerBtn_Click(object sender, EventArgs e)
{
++numberOfEntries; // "Add" clicked: we need to create one more entry
currentEntryShown = numberOfEntries - 1; // scroll to an empty record at the end
// Create a new data structure, its constructor will fill it with default values
myStruct aNewStruct = new myStruct(5);
dataList.Add(aNewStruct); // add the frshly created struct to the ArrayList
ShowData(); // display
addNewPlayerBtn.Enabled = true; // can't do this again before saving
UpdatePrevNextBtnStatus();
}
private void SaveBtn_Click(object sender, EventArgs e)
{
SaveData(); // Call the Save() method implemented below
addNewPlayerBtn.Enabled = true; // After saving we can add another new record
UpdatePrevNextBtnStatus(); // Set 'Next' and 'Previous' button appearance
}
// =========================================================================
// =========================================================================
// ================ HANDLE DATA CHANGES BY USER ============================
// =========================================================================
// If the text box string is changed by the user, update
private void playerIdBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.uniquePlayerId[0] = Convert.ToInt32(playerIdBox.Text);
dataList[currentEntryShown] = aNewStruct;
}
private void playerIgNameBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.playerIgName = playerIgNameBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactStreetBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactStreet = contactStreetBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactTownBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactTown = contactTownBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactPostcodeBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactPostcode = contactPostcodeBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactEmailBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactEmail = contactEmailBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactTelephoneBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactTelephone = contactTelephoneBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
// =========================================================================
// ================= HELPER METHODS FOR DISPLAYING DATA ====================
// =========================================================================
private void ShowData()
{
playerIdBox.Text = ((myStruct)dataList[currentEntryShown]).uniquePlayerId[0].ToString();
playerIgNameBox.Text = ((myStruct)dataList[currentEntryShown]).playerIgName;
contactStreetBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactStreet;
contactTownBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactTown;
contactPostcodeBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactPostcode;
contactEmailBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactEmail;
contactTelephoneBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactTelephone;
pathToImagePlaceholder = "" + ((myStruct)dataList[currentEntryShown]).imagePath;
MessageBox.Show(pathToImagePlaceholder);
try
{
playerPictureBox.Image = Image.FromFile(pathToImagePlaceholder);
}
catch
{
return;
}
}
private void UpdatePrevNextBtnStatus()
{
if (currentEntryShown > 0) showPreviousBtn.Enabled = true;
else showPreviousBtn.Enabled = false;
if (currentEntryShown < (numberOfEntries - 1)) showNextBtn.Enabled = true;
else showNextBtn.Enabled = false;
label1.Text = "Player ID";
label3.Text = (currentEntryShown + 1) + " / " + numberOfEntries;
}
// =========================================================================
// =========================================================================
// =============== HELPER METHODS FOR LOADING AND SAVING ===================
// =========================================================================
private void SaveData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
try
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, dataList);
MessageBox.Show("Data saved to " + filename, "FILE SAVE OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Could not serialise to " + filename,
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
fs.Close();
}
catch
{
MessageBox.Show("Could not open " + filename +
" for saving.\nNo access rights to the folder, perhaps?",
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void LoadData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
try
{
BinaryFormatter bf = new BinaryFormatter();
dataList = (ArrayList)bf.Deserialize(fs);
currentEntryShown = 0;
numberOfEntries = dataList.Count;
}
catch
{
MessageBox.Show("Could not de-serialise from " + filename +
"\nThis usually happens after you changed the data structure.\nDelete the data file and re-start program\n\nClick 'OK' to close the program",
"FILE LOADING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
fs.Close(); // close file
Environment.Exit(1); // crash out
}
fs.Close();
}
catch
{
if (MessageBox.Show("Could not open " + filename + " for loading.\nFile might not exist yet.\n(This would be normal at first start)\n\nCreate a default data file?",
"FILE LOADING PROBLEM", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
// No data exist yet. Create a first entry
myStruct aNewStruct = new myStruct(5);
dataList.Add(aNewStruct);
numberOfEntries = 1;
currentEntryShown = 0;
}
}
}
// =========================================================================
// =========================================================================
// ====================== HELPER METHODS FOR SORTING =======================
// =========================================================================
// This function will sort by player name by using the PlayerNameComparer below
private void sortToolStripMenuItem_Click(object sender, EventArgs e)
{
dataList.Sort(new PlayerNameComparer());
currentEntryShown = 0;
ShowData();
UpdatePrevNextBtnStatus();
}
// Overriding (= overwriting) the default IComparer
public class PlayerNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((myStruct)x).playerIgName.CompareTo(((myStruct)y).playerIgName);
}
}
private void saveButton_Click(object sender, EventArgs e)
{
SaveData();
UpdatePrevNextBtnStatus();
}
private void deletePlayerBtn_Click(object sender, EventArgs e)
{
dataList.RemoveAt(currentEntryShown);
SaveData();
if (currentEntryShown != dataList.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void searchToolStripMenuItem_Click(object sender, EventArgs e)
{
Form searchForm = new Form1();
searchForm.Show();
}
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog OpenFd = new OpenFileDialog();
pathToImage = OpenFd.FileName;
OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
playerPictureBox.Image = Image.FromFile(OpenFd.FileName);
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.imagePath = pathToImage;
dataList[currentEntryShown] = aNewStruct;
// save the FileName to a string.
}
MessageBox.Show(pathToImage);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
Set pathToImage after the ShowDIalog has completed, not before:
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
pathToImage = OpenFd.FileName; ...
I could be wrong because reading all that wall of code requires too much time, but your last method should be
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog OpenFd = new OpenFileDialog();
// REMOVED HERE .... pathToImage = OpenFd.FileName
OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
playerPictureBox.Image = Image.FromFile(OpenFd.FileName);
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.imagePath = OpenFd.FileName; // Changed this line...
dataList[currentEntryShown] = aNewStruct;
}
// no much sense this here if the user cancel the dialogbox
// MessageBox.Show(pathToImage);
}

Can't get list box to display SelectedText only displays "system.windows.forms.listbox+selectedobjectcollection"

I need some help i can't figure out whats wrong with my code, everytime i try to get the program to display the SelectedItems i get "system.windows.forms.listbox+selectedobjectcollection". I can get text from the combobox to the emailBankListBox1 but when i try to hop from the emailBanklistBox1 to listBox1 i get the text listed above. Any and all help is much appreciated.
private void addButton1_Click(object sender, EventArgs e)
{
/*
int selectIndexInt = -1;
selectIndexInt = recipientComboBox.SelectedIndex;
if (selectIndexInt != -1)
{
emailBankListBox1.Items.Add(recipientComboBox.SelectedItem += ",");
}
else
{
}
*/
if (recipientComboBox.Text == "")
{
MessageBox.Show("Please enter a Recipient Email");
}
else
{
emailBankListBox1.Items.Add(recipientComboBox.Text += ",");
}
for (int i = 0; i < emailBankListBox1.Items.Count; i++)
{
emailBankListBox1.SetSelected(i, true);
}
}
private void removeButton2_Click(object sender, EventArgs e)
{
int selectIndexInt = -1;
selectIndexInt = emailBankListBox1.SelectedIndex;
if (selectIndexInt != -1)
{
emailBankListBox1.Items.RemoveAt(selectIndexInt);
}
else
{
MessageBox.Show("Select a name from the 'Recipients to recieve email' List");
}
}
private void button5_Click(object sender, EventArgs e)
{
this.Close();
}
private void button4_Click(object sender, EventArgs e)
{
/*
for (int i = 0; i < emailBankListBox1.Items.Count; i++)
{
emailBankListBox1.SetSelected(i, true);
}
*/
var selectedString = emailBankListBox1.SelectedItems.ToString();
listBox1.Items.Add(selectedString);
/*
//Email sending
MailMessage myMail = new MailMessage();
myMail.To.Add(new MailAddress(emailBankListBox1.SelectedItems.ToString()));
myMail.From = new MailAddress("******m", "******");
myMail.Subject = subjectTextBox.Text;
myMail.Body = bodyTextBox.Text;
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("*********", "*****");
try
{
smtp.Send(myMail);
MessageBox.Show("Message Sent");
}
catch
{
MessageBox.Show("Cannot send this message");
}
*/
}
private void recipientComboBox_SelectedValueChanged(object sender, EventArgs e)
{
int selectIndexInt = -1;
selectIndexInt = recipientComboBox.SelectedIndex;
if (selectIndexInt != -1)
{
emailBankListBox1.Items.Add(recipientComboBox.SelectedItem += ",");
}
else
{
if (recipientComboBox.Text == "")
{
MessageBox.Show("Please type or select a recipient E-mail");
}
}
for (int i = 0; i < emailBankListBox1.Items.Count; i++)
{
emailBankListBox1.SetSelected(i, true);
}
}
SelectedItems is a collection and not an item.
You should be doing this
var selItem = emailBankListBox1.SelectedItem;
var selectedString=selItem.ToString();
var idx = emailBankListBox1.Items.IndexOf(selItem);
You are essentially calling ToString on a collection. If you want to add each selected item to a separate listbox, you could do:
foreach(var item in emailBankListBox1.SelectedItems)
listBox1.Items.Add(item.ToString());
If you Linq, you can directly do:
listBox1.Items.AddRange(emailBankListBox1.SelectedItems.OfType<string>());
If your objects inside emailBankListBox1 are not merely strings, then you will have to set the display member property in listbox1

C# button not returning expected value

I have a windows ATM app and I'm stuck on this part:
I have pin and firstName as private strings and balance as private double.
However, when I try to display the balance in the text area, it just prints 0. Is it because retrieveAccountInformation() has void as the return? How can I change my code so that I can use pin, firstName, and balance in my other methods?
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 SQLDll;
namespace WindowsFormsApplication14
{
public partial class Form1 : Form
{
private Connection myConnection;
private Statement myStatement;
private ResultSet myResultSet;
String databaseURL = "http://www.boehnecamp.com/phpMyAdmin/razorsql_mysql_bridge.php";
public string pin, firstName, userAccountNumber;
public double balance;
public double withdraw = 0;
public double deposit = 0;
bool buttonClicked;
bool buttonClicked2;
public Form1()
{
InitializeComponent();
try
{
//connect to database
SQL sql = new SQL();
myConnection = sql.getConnection(databaseURL);
//create Statement for executing SQL
myStatement = myConnection.createStatement(databaseURL);
loadAccountNumbers();
updateBalance();
}
catch (Exception)
{
Console.WriteLine("Cannot connect to database server");
}
//close statement and database connection
myStatement.close();
myConnection.close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void setText(string text)
{
}
//load account numbers to ComboBox
private void loadAccountNumbers()
{
//get all account numbers from database
try
{
myResultSet = myStatement.executeQuery("SELECT accountNumber FROM accountInformation");
// add account numbers to ComboBox
while (myResultSet.next())
{
accountNumberComboBox.Items.Add(myResultSet.getString("accountNumber"));
}
myResultSet.close(); // close myResultSet
}//end try
catch (Exception)
{
Console.WriteLine("Error in loadAccountNumbers");
}
}//end method to loadAccountNumbers
private void retrieveAccountInformation()
{
//get account info
try
{
myResultSet = myStatement.executeQuery("SELECT pin, " +
"firstName, balanceAmount FROM accountInformation " +
"WHERE accountNumber = '" + userAccountNumber + "'");
//get next result
if (myResultSet.next())
{
pin = myResultSet.getString("pin");
firstName = myResultSet.getString("firstName");
balance = myResultSet.getDouble("balanceAmount");
}
myResultSet.close(); //close myResultSet
}//end try
catch (Exception)
{
Console.WriteLine("Error in retrieveAccountInformation");
}
}// end method retrieveAccountInformation
//update database after withdrawing
private void updateBalance()
{
//update balance in database
try
{
myStatement.executeUpdate("UPDATE accountInformation" +
" SET balanceAmount = " + balance + " WHERE " +
"accountNumber = '" + userAccountNumber + "'");
}
catch (Exception)
{
Console.WriteLine("Error in updateBalace");
}
}//end method updateBalance
private void accountNumberComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
accountNumberComboBox.Enabled = false;
numberTextField.Text = " ";
messageTextArea.Text = "Enter your PIN #.";
button0.Enabled = true;
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
button8.Enabled = true;
button9.Enabled = true;
buttonDone.Enabled = true;
retrieveAccountInformation();
}
private void button1_Click(object sender, EventArgs e)
{
setText("1");
numberTextField.Text += "1";
buttonEnter.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
setText("2");
numberTextField.Text += "2";
buttonEnter.Enabled = true;
}
private void button3_Click(object sender, EventArgs e)
{
setText("3");
numberTextField.Text += "3";
buttonEnter.Enabled = true;
}
private void button4_Click(object sender, EventArgs e)
{
setText("4");
numberTextField.Text += "4";
buttonEnter.Enabled = true;
}
private void button5_Click(object sender, EventArgs e)
{
setText("5");
numberTextField.Text += "5";
buttonEnter.Enabled = true;
}
private void button6_Click(object sender, EventArgs e)
{
setText("6");
numberTextField.Text += "6";
buttonEnter.Enabled = true;
}
private void button7_Click(object sender, EventArgs e)
{
setText("7");
numberTextField.Text += "7";
buttonEnter.Enabled = true;
}
private void button8_Click(object sender, EventArgs e)
{
setText("8");
numberTextField.Text += "8";
buttonEnter.Enabled = true;
}
private void button9_Click(object sender, EventArgs e)
{
setText("9");
numberTextField.Text += "9";
buttonEnter.Enabled = true;
}
private void button0_Click(object sender, EventArgs e)
{
setText("0");
numberTextField.Text += "0";
buttonEnter.Enabled = true;
}
private void buttonEnter_Click(object sender, EventArgs e)
{
numberTextField.Text = " ";
buttonEnter.Enabled = false;
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
button5.Enabled = false;
button6.Enabled = false;
button7.Enabled = false;
button8.Enabled = false;
button9.Enabled = false;
button0.Enabled = false;
buttonBalance.Enabled = true;
buttonWithdraw.Enabled = true;
buttonDeposit.Enabled = true;
messageTextArea.Text = "Welcome," + firstName;
updateBalance();
if (buttonClicked == true)
{
withdraw = Double.Parse(numberTextField.Text);
balance = balance - withdraw;
updateBalance();
}
}
private void buttonBalance_Click(object sender, EventArgs e)
{
retrieveAccountInformation();
updateBalance();
messageTextArea.Text=(balance.ToString());
//display balance to messageTextArea
}
private void buttonWithdraw_Click(object sender, EventArgs e)
{
buttonBalance.Enabled = false;
buttonWithdraw.Enabled = false;
button0.Enabled = true;
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
button8.Enabled = true;
button9.Enabled = true;
messageTextArea.Text = "Enter withdrawal amount:";
buttonClicked = true;
}
private void buttonDone_Click(object sender, EventArgs e)
{
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
button5.Enabled = false;
button6.Enabled = false;
button7.Enabled = false;
button8.Enabled = false;
button9.Enabled = false;
button0.Enabled = false;
buttonEnter.Enabled = false;
buttonBalance.Enabled = false;
buttonWithdraw.Enabled = false;
buttonDone.Enabled = false;
buttonDeposit.Enabled = false;
accountNumberComboBox.Enabled = true;
messageTextArea.Text = "Please select your account number.";
}
private void buttonDeposit_Click(object sender, EventArgs e)
{
buttonBalance.Enabled = false;
buttonWithdraw.Enabled = false;
button0.Enabled = true;
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
button8.Enabled = true;
button9.Enabled = true;
messageTextArea.Text = "Enter deposit amount:";
buttonClicked2 = true;
}
}
}
Because you are using myResultSet.next().
If you have two SQL Statements, eg
SELECT * FROM Users
Go
SELECT * FROM Accounts
Go
if (myResultSet.next()) -> this will read the data returned from the second SQL Statement.
I think this maybe what you are wanting:
string connString = AppConfigurationManager.GetAppSetting("ConnectionString",IsQA);
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand sqlCommand = new SqlCommand("SELECT pin, " +
"firstName, balanceAmount FROM accountInformation " +
"WHERE accountNumber = '" + userAccountNumber + "'", conn))
{
sqlCommand.CommandType = CommandType.Text;
SqlDataReader dr = null;
try
{
dr = sqlCommand.ExecuteReader();
while (dr.Read())
{
pin = dr.getString("pin");
firstName = dr.getString("firstName");
balance = dr.getDouble("balanceAmount");
}
}
catch (SqlException ex)
{
}
catch (Exception ex)
{
}
finally
{
//clean up resources that access Data
if (dr != null)
{
dr.Close();
}
}
}
you can using "out" or "ref" in my opinion
private void retrieveAccountInformation(out string pin, out string firstname, out double balance)
{
//get account info
try
{
myResultSet = myStatement.executeQuery("SELECT pin, " +
"firstName, balanceAmount FROM accountInformation " +
"WHERE accountNumber = '" + userAccountNumber + "'");
//get next result
if (myResultSet.next())
{
pin = myResultSet.getString("pin");
firstName = myResultSet.getString("firstName");
balance = myResultSet.getDouble("balanceAmount");
}
myResultSet.close(); //close myResultSet
}//end try
catch (Exception)
{
Console.WriteLine("Error in retrieveAccountInformation");
}
}// end method retrieveAccountInformation
private void buttonBalance_Click(object sender, EventArgs e)
{
string pin = "";
string firstname = "";
double balance = 0;
retrieveAccountInformation(out string pin, out string firstname, out double balance);
updateBalance();
messageTextArea.Text=(balance.ToString());
//display balance to messageTextArea
}
Because pin, firstName, balance is Local Variable and this method is private void so if you want to get value from a void method. Use in,out variable. This make a method can return multiple value
Morever, what updateBalance() do ? It declared varial and call retrieveAccountInformation method ????
Example :
private void retrieveAccountInformation(out string pin,out string firstname,out double balance)
{
//get account info
try
{
myResultSet = myStatement.executeQuery("SELECT pin, " +
"firstName, balanceAmount FROM accountInformation " +
"WHERE accountNumber = '" + userAccountNumber + "'");
//get next result
if (myResultSet.next())
{
pin = myResultSet.getString("pin");
firstName = myResultSet.getString("firstName");
balance = myResultSet.getDouble("balanceAmount");
}
myResultSet.close(); //close myResultSet
}//end try
catch (Exception)
{
Console.WriteLine("Error in retrieveAccountInformation");
}
}// end method retrieveAccountInformation
private void buttonBalance_Click(object sender, EventArgs e)
{
string pin, firstname;
double balance;
retrieveAccountInformation(pin, firstname, balance);
messageTextArea.Text=(balance.ToString());
//display balance to messageTextArea
}

Categories