C# trying to cleanup code by using generic class - c#

at the moment everything I want working is good. But I am trying to clean it up a bit and was looking for some advice when using a generic class. I want to take void update, void add, and void delete and move it to another class then call it in my form when needed. My guess was to try using something like _delete then getters and setters but whenever i tried that i would get errors because I cant recognize listView1. Could someone point me in the right direction? My code is below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace cartest
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
listView1.View = View.Details;
listView1.FullRowSelect = true;
listView1.Columns.Add("Make", 60);
listView1.Columns.Add("Model", 60);
listView1.Columns.Add("Color", 50);
listView1.Columns.Add("Miles", 50);
listView1.Columns.Add("Condition", 90);
listView1.Columns.Add("Interior", 60);
listView1.Columns.Add("Highway MPG", 90);
listView1.Columns.Add("City MPG", 90);
listView1.Columns.Add("Price", 50);
}
private void add(string make, string model, string color, string miles, string condition, string interior, string highway, string city, string price)
{
string[] row = { make, model, color, miles, condition, interior, highway, city, price }; //adding rows to list
ListViewItem item = new ListViewItem(row);
listView1.Items.Add(item);
}
private void update()
{
listView1.SelectedItems[0].SubItems[0].Text = textBoxMake.Text;
listView1.SelectedItems[0].SubItems[0].Text = textBoxModel.Text;
listView1.SelectedItems[0].SubItems[0].Text = textBoxColor.Text;
listView1.SelectedItems[0].SubItems[0].Text = textBoxMiles.Text;
listView1.SelectedItems[0].SubItems[0].Text = textBoxCondition.Text;
listView1.SelectedItems[0].SubItems[0].Text = textBoxInterior.Text;
listView1.SelectedItems[0].SubItems[0].Text = textBoxHighway.Text;
listView1.SelectedItems[0].SubItems[0].Text = textBoxCity.Text;
listView1.SelectedItems[0].SubItems[0].Text = textBoxPrice.Text;
//After you update an item it clears the text
textBoxMake.Text = ""; textBoxModel.Text = ""; textBoxColor.Text = ""; textBoxMiles.Text = ""; textBoxCondition.Text = ""; textBoxInterior.Text = ""; textBoxHighway.Text = ""; textBoxCity.Text = ""; textBoxPrice.Text = "";
}
//delete from list
private void delete()
{
if (MessageBox.Show("Are you sure you want to delete this item?", "Delete", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
listView1.Items.RemoveAt(listView1.SelectedIndices[0]);
//After you delete it clears text
textBoxMake.Text = ""; textBoxModel.Text = ""; textBoxColor.Text = ""; textBoxMiles.Text = ""; textBoxCondition.Text = ""; textBoxInterior.Text = ""; textBoxHighway.Text = ""; textBoxCity.Text = ""; textBoxPrice.Text = "";
}
}
// add to list
private void buttonAdd_Click(object sender, EventArgs e)
{
add(textBoxMake.Text, textBoxModel.Text, textBoxColor.Text, textBoxMiles.Text, textBoxCondition.Text, textBoxInterior.Text, textBoxHighway.Text, textBoxCity.Text, textBoxPrice.Text);
//After you add an item to list it clears text
textBoxMake.Text = ""; textBoxModel.Text = ""; textBoxColor.Text = ""; textBoxMiles.Text = ""; textBoxCondition.Text = ""; textBoxInterior.Text = ""; textBoxHighway.Text = ""; textBoxCity.Text = ""; textBoxPrice.Text = "";
}
//update item in list
private void buttonUpdate_Click(object sender, EventArgs e)
{
update();
}
//delete a item in list
private void buttonDelete_Click(object sender, EventArgs e)
{
delete();
}
//Click on an item, you get all the values in that row into the textbox
//Used for update purposes
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
textBoxMake.Text = listView1.SelectedItems[0].SubItems[0].Text;
textBoxModel.Text = listView1.SelectedItems[0].SubItems[1].Text;
textBoxColor.Text = listView1.SelectedItems[0].SubItems[2].Text;
textBoxMiles.Text = listView1.SelectedItems[0].SubItems[3].Text;
textBoxCondition.Text = listView1.SelectedItems[0].SubItems[4].Text;
textBoxInterior.Text = listView1.SelectedItems[0].SubItems[5].Text;
textBoxHighway.Text = listView1.SelectedItems[0].SubItems[6].Text;
textBoxCity.Text = listView1.SelectedItems[0].SubItems[7].Text;
textBoxPrice.Text = listView1.SelectedItems[0].SubItems[8].Text;
}
private void buttonSearch_Click(object sender, EventArgs e)
{
}
private void buttonSave_Click(object sender, EventArgs e)
{
string make = textBoxMake.Text;
string model = textBoxModel.Text;
string color = textBoxModel.Text;
string miles = textBoxModel.Text;
string condition = textBoxModel.Text;
string interior = textBoxModel.Text;
string highway = textBoxModel.Text;
string city = textBoxCity.Text;
string price = textBoxPrice.Text;
openFileDialog1.FileName = "cars";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
using (StreamWriter ap = File.AppendText("cars.txt"))
{
ap.WriteLine(make);
ap.WriteLine(model);
ap.WriteLine(color);
ap.WriteLine(miles);
ap.WriteLine(condition);
ap.WriteLine(interior);
ap.WriteLine(highway);
ap.WriteLine(city);
ap.WriteLine(price);
}
}
}
private void buttonLoad_Click(object sender, EventArgs e)
{
var fileLines = File.ReadAllLines(#"C:\Users\Tyler\Documents\Visual Studio 2015\Projects\Prac\FinalProject\FinalProject\bin\Debug\cars.txt");
for (int i = 0; i + 7 < fileLines.Length; i += 8)
{
listView1.Items.Add(
new ListViewItem(new[]
{
fileLines[i],
fileLines[i + 1],
fileLines[i + 2],
fileLines[i + 3],
fileLines[i + 4],
fileLines[i + 5],
fileLines[i + 6],
fileLines[i + 7],
fileLines[i + 8]
}));
}
}
}
}

Be careful of your usage of the word "generic". Generic class means something very specific in C#. It looks like what you're actually trying to do is just move some functionality out of the form into a separate class. The way to accomplish that might be to pass listView1 into your new class' constructor, which would store it in a class member for add, delete, and move to reference when they're called.
Something like this:
public class MyClass
{
private ListView listView;
public MyClass(ListView lv)
{
listView = lv;
}
public void add(string make, string model, string color, string miles, string condition, string interior, string highway, string city, string price)
{
string[] row = { make, model, color, miles, condition, interior, highway, city, price }; //adding rows to list
ListViewItem item = new ListViewItem(row);
listView.Items.Add(item);
}
// Delete method goes here
// Move method goes here
}
Then to use it, you could do something like:
private void buttonAdd_Click(object sender, EventArgs e)
{
MyClass foo = new MyClass(listView1);
foo.add(textBoxMake.Text, textBoxModel.Text, textBoxColor.Text, textBoxMiles.Text, textBoxCondition.Text, textBoxInterior.Text, textBoxHighway.Text, textBoxCity.Text, textBoxPrice.Text);
... // More code
}

Related

How to use Multi threading in my project?

I am practicing an OCR program using C#, I am not much of a coder so I am trying to find my way around.
1- I OCR some pdf files.
2- I see the output of the OCR.
3- I use UI buttons to browse and then click convert.
4- I have a progress bar on the UI but it does not visually upgrade, while when I log the progressBar.Value I see its numbers are updating.
So I searched around and I found that the issue is I should like stop the thread and create a new one for the Ui to visually update, but I really do not understand that, or even do not know how to do it.
Can someone please help me ? like baby steps.
Also I know I have copied and pasted like alot of code for you to see.
The case is the following:
1- class fmMain: Form has a progressBarIncrementation function, responsible for taking the increment value from a function in processFunctions class.
2- progressBarIncrementation function has progressBar.Value to be updated, I see its value updated.
3- But visually nothing is updated. I tried some threading code, but i do not understand it so.....
class processFunctions
{
Thread newThread = Thread.CurrentThread;
private string invoiceNameIndex = "";
private string invoiceIBANIndex = "";
private string invoiceNumberIndex = "";
private string invoiceDateIndex = "";
private string invoiceSubtotalIndex = "";
private string invoiceVATIndex = "";
private string invoiceTotalIndex = "";
private string[] filePath;
private string[] fileNamePDF;
private int totalNumberOfFiles;
private string InformationNeeded(string wholeRead, string ix)
{
string[] lines = wholeRead.Split(new[] { "\r\n", "\r", "\n", " " }, StringSplitOptions.None);
if(ix.Contains(","))
{
string[] variableIndex = ix.Split(',');
string name = "";
for(int i =0; i < variableIndex.Length; i++)
{
name += lines[Convert.ToInt32(variableIndex[i])];
}
return name;
}
return lines[Convert.ToInt32(ix)];
}
public void ocrFunction(string filePathOnly)
{
var Ocr = new AutoOcr();
var Results = Ocr.ReadPdf(filePathOnly);
var Barcodes = Results.Barcodes;
var Text = Results.Text;
string[] numbers = { invoiceNameIndex, invoiceIBANIndex, invoiceNumberIndex,
invoiceDateIndex, invoiceSubtotalIndex, invoiceVATIndex, invoiceTotalIndex};
string[] results = new string[numbers.Count()];
for (int i = 0; i < numbers.Length; i++)
{
results[i] = InformationNeeded(Text, numbers[i]);
Console.WriteLine(results[i]);
}
Results = null;
Ocr = null;
Barcodes = null;
Text = null;
}
public int browseFile()
{
Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
OpenFileDialog ofd = new OpenFileDialog();
int numberOfFilesToBeProcessed = 0;
ofd.Filter = "PDF|*.pdf";
ofd.Multiselect = true;
string[] name = new string[2];
if (ofd.ShowDialog() == DialogResult.OK)
{
numberOfFilesToBeProcessed = ofd.FileNames.Length;
filePath = ofd.FileNames;
fileNamePDF = ofd.SafeFileNames;
}
this.totalNumberOfFiles = ofd.FileNames.Length;
return numberOfFilesToBeProcessed;
}
public void databaseReader()
{
string connectionString;
SqlConnection connection;
connectionString = ConfigurationManager.ConnectionStrings["OCR_App.Properties.Settings.LibraryConnectionString"].ConnectionString;
for (int i = 0; i < fileNamePDF.Length; i++)
{
string fileNameFiltered = fileNamePDF[i].Replace(".pdf", "");
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM invoicesTable WHERE invoiceRef = '" + fileNameFiltered + "'", connection))
{
DataTable invoicesTable = new DataTable();
adapter.Fill(invoicesTable);
DataRow index = invoicesTable.Rows[0];
invoiceNameIndex = (index[1].ToString());
invoiceIBANIndex = (index[2].ToString());
invoiceNumberIndex = (index[3].ToString());
invoiceDateIndex = (index[4].ToString());
invoiceSubtotalIndex = (index[5].ToString());
invoiceVATIndex = (index[6].ToString());
invoiceTotalIndex = (index[7].ToString());
ocrFunction(filePath[i]);
//newThread.Start();
fmMain formFunctions = new fmMain();
//Thread.Yield();
//Thread thread = new Thread(() => formFunctions.ProgressBarIncrementation(progressBarIncrement()));
formFunctions.ProgressBarIncrementation(progressBarIncrement());
}
}
}
public int progressBarIncrement()
{
int incrementValue = 0;
incrementValue = incrementValue + 100 / totalNumberOfFiles;
//Console.WriteLine(incrementValue);
return incrementValue;
}
///////////////////////////////////////////////////////////////////
public partial class fmMain : Form
{
processFunctions processingMain = new processFunctions();
ProgressBar NewprogressBar = new ProgressBar();
private static int incrementbar = 0;
public fmMain()
{
InitializeComponent();
}
[STAThread]
private void BtnBrowse_Click(object sender, EventArgs e)
//Browse the file needed to scan.
{
int number = processingMain.browseFile();
txtBoxFilePath.Text = number.ToString();
}
public void BtnConvert_Click(object sender, EventArgs e)
{
processingMain.databaseReader();
}
private void fmMain_Load(object sender, EventArgs e)
{
}
private void txtBoxFilePath_TextChanged(object sender, EventArgs e)
{
}
private void NumberOfFilesToBeProcessed_Click(object sender,
EventArgs e)
{
}
public void progressBar_Click(object sender, EventArgs e)
{
progressBar.Maximum = 100;
NewprogressBar.Value = progressBar.Value;
}
public void ProgressBarIncrementation(int incrementValue)
{
//Thread.Yield();
//Thread newThread = Thread.CurrentThread;
incrementbar = incrementbar + incrementValue;
progressBar.Visible = true;
progressBar.Value += incrementbar;
Thread thread = new Thread(() => progressBar.Value += incrementbar);
Console.WriteLine(progressBar.Value);
//progressBar.Value += incrementbar;
}
}
If you are needing the progress bar, you might want to consider creating an event to help report progress to your calling application. And you'll want to mark your function browseFile as async and do the following:
public async Task<int> browseFileAsync()
{
await Task.Run(new Action(() => {
OpenFileDialog ofd = new OpenFileDialog();
int numberOfFilesToBeProcessed = 0;
ofd.Filter = "PDF|*.pdf";
ofd.Multiselect = true;
string[] name = new string[2];
if (ofd.ShowDialog() == DialogResult.OK)
{
numberOfFilesToBeProcessed = ofd.FileNames.Length;
filePath = ofd.FileNames;
fileNamePDF = ofd.SafeFileNames;
}
this.totalNumberOfFiles = ofd.FileNames.Length;
return numberOfFilesToBeProcessed;
}));
}
And then in your calling application do:
private async void BtnBrowse_Click(object sender, EventArgs e)
//Browse the file needed to scan.
{
int number = await processMain.browseFileAsync();
txtBoxFilePath.Text = number.ToString();
}
I would also consider not calling a folder browser dialog from your class as this couples your class to a specific implementation. Rather, I would browse for the file from the GUI and pass the selected file(s) to the class.

C# How to shorten Datagridview Selectionchanged code in a clean and proper way of coding

I always wanted my code to be cleaner and readable. I'm here in order to achieve that. Since i'm a beginner, it's better to learn this early. Like calling all of them in a class, I don't want too see these many codes in my form. I hope someone would be able to give me a suggestions and a proper way of doing these.
Here's my code
public partial class SIMSSupplier : UserControl
{
ADDSupplier supply;
ADDPReturns returns;
public SIMSSupplier()
{
InitializeComponent();
}
public DataTable dbdataset;
public DataSet ds = new DataSet();
public string ID = "SPPLR-000";
public int DeliveryID, OrderID, ReturnID;
DataView db;
DataTable dt = new DataTable();
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
var row = Supplierview.CurrentCell.RowIndex;
SupplierID.Text = Supplierview.Rows[row].Cells[0].Value.ToString();
CompanyName.Text = Supplierview.Rows[row].Cells[1].Value.ToString();
ContactName.Text = Supplierview.Rows[row].Cells[2].Value.ToString();
ContactNumber.Text = Supplierview.Rows[row].Cells[3].Value.ToString();
Date.Text = Supplierview.Rows[row].Cells[4].Value.ToString();
Address.Text = Supplierview.Rows[row].Cells[5].Value.ToString();
Remarks.Text = Supplierview.Rows[row].Cells[6].Value.ToString();
}
private void PurchaseOrder_SelectionChanged(object sender, EventArgs e)
{
var row = PurchaseOrder.CurrentCell.RowIndex;
txt_purchase.Text = PurchaseDeliveries.Rows[row].Cells[0].Value.ToString();
txt_supplier.Text = PurchaseDeliveries.Rows[row].Cells[1].Value.ToString();
txt_item.Text = PurchaseDeliveries.Rows[row].Cells[2].Value.ToString();
txt_date.Text = PurchaseDeliveries.Rows[row].Cells[3].Value.ToString();
txt_quantity.Text = PurchaseDeliveries.Rows[row].Cells[4].Value.ToString();
txt_cost.Text = PurchaseDeliveries.Rows[row].Cells[5].Value.ToString();
txt_amount.Text = PurchaseDeliveries.Rows[row].Cells[6].Value.ToString();
txt_sales.Text = PurchaseDeliveries.Rows[row].Cells[7].Value.ToString();
txt_code.Text = PurchaseDeliveries.Rows[row].Cells[8].Value.ToString();
txt_patient.Text = PurchaseDeliveries.Rows[row].Cells[9].Value.ToString();
}
private void PurchaseDeliveries_SelectionChanged(object sender, EventArgs e)
{
var row = PurchaseDeliveries.CurrentCell.RowIndex;
PurchaseID.Text = PurchaseDeliveries.Rows[row].Cells[0].Value.ToString();
Supplier.Text = PurchaseDeliveries.Rows[row].Cells[1].Value.ToString();
ItemDescription.Text = PurchaseDeliveries.Rows[row].Cells[2].Value.ToString();
Dates.Text = PurchaseDeliveries.Rows[row].Cells[3].Value.ToString();
Quantity.Text = PurchaseDeliveries.Rows[row].Cells[4].Value.ToString();
Unitcost.Text = PurchaseDeliveries.Rows[row].Cells[5].Value.ToString();
Amount.Text = PurchaseDeliveries.Rows[row].Cells[6].Value.ToString();
SalesInvoice.Text = PurchaseDeliveries.Rows[row].Cells[7].Value.ToString();
Codeitems.Text = PurchaseDeliveries.Rows[row].Cells[8].Value.ToString();
Patientname.Text = PurchaseDeliveries.Rows[row].Cells[9].Value.ToString();
}
private void PurchaseReturn_SelectionChanged(object sender, EventArgs e)
{
var row = PurchaseReturn.CurrentCell.RowIndex;
txt_return.Text = PurchaseReturn.Rows[row].Cells[0].Value.ToString();
txt_rsupplier.Text = PurchaseReturn.Rows[row].Cells[1].Value.ToString();
txt_ritem.Text = PurchaseReturn.Rows[row].Cells[2].Value.ToString();
txt_rmodel.Text = PurchaseReturn.Rows[row].Cells[3].Value.ToString();
txt_rsrp.Text = PurchaseReturn.Rows[row].Cells[4].Value.ToString();
txt_rcode.Text = PurchaseReturn.Rows[row].Cells[5].Value.ToString();
txt_rdate.Text = PurchaseReturn.Rows[row].Cells[6].Value.ToString();
txt_rremarks.Text = PurchaseReturn.Rows[row].Cells[7].Value.ToString();
}
}
the first can simplify as the following:
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
var row = Supplierview.CurrentRow;
SupplierID.Text = row.Cells[0].Value.ToString();
CompanyName.Text = row.Cells[1].Value.ToString();
ContactName.Text = row.Cells[2].Value.ToString();
ContactNumber.Text = row.Cells[3].Value.ToString();
Date.Text = row.Cells[4].Value.ToString();
Address.Text = row.Cells[5].Value.ToString();
Remarks.Text = row.Cells[6].Value.ToString();
}
the second , i would recommend use objects collection as a datasource for your grid. For example :
class DataItem{
public string SupplierID {get;set;}
public string CompanyName {get;set;}
.....
}
Supplierview.DataSource = "collection of DataItem"
then
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
var dataItem = dataGridView1.CurrentRow.DataBoundItem as DataItem;
if (dataItem != null)
{
SupplierID.Text = dataItem.SupplierID;
.....
}
}
I suggest using DataBinding for this, then there is no code needed to perform the actions in your sample.
If you dont want to use databinding you could simply make use of private methods to organize your code.
For example
#region Supplier Stuff
private void SupplierViewChanged(DataRow row)
{
SupplierID.Text = row.Cells[0].Value.ToString();
CompanyName.Text = row.Cells[1].Value.ToString();
ContactName.Text = row.Cells[2].Value.ToString();
ContactNumber.Text = row.Cells[3].Value.ToString();
Date.Text = row.Cells[4].Value.ToString();
Address.Text = row.Cells[5].Value.ToString();
Remarks.Text = row.Cells[6].Value.ToString();
}
// put all other helper methods that deal with Supplier here...
#endregion Supplier Stuff
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
SupplierViewChanged(Supplierview.CurrentRow);
}
This makes your code a bit more organized and readable, but databinding is still the method I would choose

How to fix the drag and drop using dev express in c# after fetching data and setting tag property

enter image description here
namespace Implementer
{
public partial class MainForm : Form
{
#region intit and globals
public MainForm()
{
InitializeComponent();
DevExpress.XtraGrid.Views.Grid.GridView gridView = new DevExpress.XtraGrid.Views.Grid.GridView();
var transactions = new ObservableCollection<Item>();
for (int i = 0; i <= 100; i++)
{
transactions.Add(new Item { Content = "Item " + i });
}
grdTransactions.AllowDrop = true;
grdTransactions.DataSource = transactions;
dgmWf.AddingNewItem += (s, e) => transactions.Remove(e.Item.Tag as Item);
}
Point mouseDownLocation;
GridHitInfo gridHitInfo;
#endregion
#region events
public void Mainform_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'vA_ERP4_ADMINDataSet.SYSTEM_MODULES' table. You can move, or remove it, as needed.
//Project initiation
//Fill drop down for project list
cmbProject.SelectedIndex = 0;
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable dtResult = dataAccess.ExecuteQueryDataSet("select MODULE_CODE, MODULE_DESC from SYSTEM_MODULES where module_is_active=1").Tables[0];
cmbProject.DisplayMember = "MODULE_DESC";
cmbProject.ValueMember = "MODULE_CODE";
cmbProject.DataSource = dtResult;
}
private void cmbProject_SelectedIndexChanged(object sender, EventArgs e)
{
lblCurrentProject.Text = cmbProject.Text;
if (cmbProject.Text != null)
{
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable dtTransactions = dataAccess.ExecuteQueryDataSet("select sys_trans_id, sys_trans_desc1 from WF_SYSTEM_TRANS where MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
grdTransactions.DataSource = dtTransactions;
}
}
private void btnSalesInvoice_Click(object sender, EventArgs e)
{
int sysTransId = 1001;
FillTransactionDetails(sysTransId);
}
#endregion
#region drag drop
private void grdTransactions_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && CanStartDragDrop(e.Location))
{
StartDragDrop();
}
}
private void grdTransactions_MouseDown(object sender, MouseEventArgs e)
{
gridHitInfo = grdVTransactions.CalcHitInfo(e.Location);
mouseDownLocation = e.Location;
}
private void grdTransactions_MouseLeave(object sender, EventArgs e)
{
if (gridHitInfo != null)
gridHitInfo.View.ResetCursor();
gridHitInfo = null;
}
private bool CanStartDragDrop(Point location)
{
return gridHitInfo.InDataRow && (Math.Abs(location.X - mouseDownLocation.X) > 2 || Math.Abs(location.Y - mouseDownLocation.Y) > 2);
}
public void StartDragDrop()
{
var draggedRow = gridHitInfo.View.GetRow(gridHitInfo.RowHandle) as Item;
var tool = new FactoryItemTool(" ", () => " ", diagram => new DiagramShape(BasicShapes.Rectangle) { Content = draggedRow.Content, Tag = draggedRow }, new System.Windows.Size(150, 100), false);
dgmWf.Commands.Execute(DiagramCommandsBase.StartDragToolCommand, tool, null);
}
#endregion
#region function
private void FillTransactionDetails(int systemTransactionId)
{
//Fill document
//Fill steps
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable transactionDetails = dataAccess.ExecuteQueryDataSet("SELECT DOC_TYPE_DESC1 FROM WF_SYSTEM_TRANS_DT WHERE SYS_TRANS_ID=1001 and MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
transactionDetails.Rows.Add();
grdDocuments.DataSource = transactionDetails;
grdDocuments.Columns["Details"].DisplayIndex = 2;
grdDocuments.Columns["Delete"].DisplayIndex = 2;
DataTable transactionSteps = dataAccess.ExecuteQueryDataSet("select WF_STEP_DESC1 from WF_STEPS where wf_id= 10101 and MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
transactionSteps.Rows.Add();
grdSteps.DataSource = transactionSteps;
}
#endregion
}
public class Item
{
public string Content { get; set; }
}
}
I don't really know where is the mistake and have been looking at it for the past few days and searching for an answer but no luck so I'd be so happy if you could help me out. It was working without the data fetching. but after calling the data it doesn't work. drag it from the grid view and when it reaches the diagram control it would turn into a rectangle with a tag property of it's ID.. With regards to the connection string.. I created a global function to just call it on the main form.

how can i invoke a method when variable value change [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Web;
using System.Net;
namespace CS_Ex1
{
public partial class Form1 : Form
{
private string tb1, tb2;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Connect_Click(object sender, EventArgs e)
{
WSMBT.Result Result;
wsmbtControl1.Mode = WSMBT.Mode.TCP_IP;
wsmbtControl1.ResponseTimeout = 1000;
Result = wsmbtControl1.Connect("127.0.0.1", 502);
if (Result != WSMBT.Result.SUCCESS)
MessageBox.Show(wsmbtControl1.GetLastErrorString());
}
private void Disconnect_Click_1(object sender, EventArgs e)
{
wsmbtControl1.Close();
}
private void button1_Click(object sender, EventArgs e)
{
Int16[] Registers = new Int16[20];
WSMBT.Result Result;
Result = wsmbtControl1.ReadHoldingRegisters(1, 0, 20, Registers);
if (Result == WSMBT.Result.SUCCESS)
{
string DataString = "";
string str = "";
for (int i = 0; i < 20; i++)
{
str = string.Format("{0:D}", Registers[0]);
str = string.Format("{0:D}", Registers[1]);
DataString = DataString + str + "\r\n";
}
TextBox1.Text = Registers[0].ToString();
TextBox2.Text = Registers[1].ToString();
tb1 = TextBox1.Text.ToString();
tb2 = TextBox2.Text.ToString();
}
else
{
MessageBox.Show(wsmbtControl1.GetLastErrorString());
}
}
private void Write_Click(object sender, EventArgs e)
{
Int16[] Registers = new Int16[20];
WSMBT.Result Result;
for (Int16 i = 0; i < 20; i++)
Registers[i] = i;
Result = wsmbtControl1.WriteMultipleRegisters(1, 0, 20, Registers);
if (Result != WSMBT.Result.SUCCESS)
{
MessageBox.Show(wsmbtControl1.GetLastErrorString());
}
}
public static void message_Click()
{
string senderusername = "XXX";
string senderpassword = "XXXX";
string senderid = "22687";
string sURL;
StreamReader objReader;
sURL = "URL";
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(sURL);
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}
}
}
In this Code VARIABLE tb1 is getting change all the time i want to invoke message_click() method which will send sms to user mobile when tb1 value gets change or suppose its value was 10 and then tb1 value changed to 68 then it should invoke message_click () and send sms
You can use a property for this. In the setter you can call the desired method after the variable has been changed:
public partial class Form1 : Form
{
private tb2;
private string _tb1;
public string tb1
{
get { return _tb1; }
private set
{
_tb1 = value;
message_click();
}
}
public Form1()
{
InitializeComponent();
}
Note that although the property is public you can make the setter private so that the variable cannot be changed outside of this class. You could also use protected:
protected string tb1
{ ...

How can i make that if an item in a listBox is out of the bound on the right so it will move one line down?

I have this code in a new Form where i add text to a textBox and then it's added to the listBox as item:
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;
namespace GatherLinks
{
public partial class ChangeLink : Form
{
public ChangeLink()
{
InitializeComponent();
}
public string getText()
{
return textBox1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
DialogResult = DialogResult.OK;
}
else
{
}
}
private void ChangeLink_Load(object sender, EventArgs e)
{
this.AcceptButton = button1;
}
}
}
And this is how i add the text to the listBox:
private void button2_Click(object sender, EventArgs e)
{
cl = new ChangeLink();
cl.StartPosition = FormStartPosition.CenterParent;
DialogResult dr = cl.ShowDialog(this);
if (dr == DialogResult.Cancel)
{
cl.Close();
}
else if (dr == DialogResult.OK)
{
label4.Text = cl.getText();
mainUrl = cl.getText();
if (!LocalyKeyWords.ContainsKey(mainUrl))
{
newUrl = true;
KeysValuesUpdate();
}
else
{
newUrl = false;
KeysValuesUpdate();
}
OptionsDB.set_changeWebSite(cl.getText());
cl.Close();
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
}
The problem is if the text was very long so in the right bound/border of the listBox the text of the item is cut. So to see it i want somehow to move it one line down or how much lines need to show the rest of the item text/name
So it will count as one item but if needed on some lines.
Update:
This is the part where i load the items to the listBox when im running my application:
private void ListBoxLoadKeys(Dictionary<string, List<string>> dictionary, string FileName)
{
int t = listBox1.Width;
using (StreamReader sr = new StreamReader(FileName))
{
while ((line = sr.ReadLine()) != null)
{
int i = line.Count();
tokens = line.Split(',');
dictionary.Add(tokens[0], tokens.Skip(1).ToList());
string tt = tokens[1].Substring(t - tokens[1].Length);
data.Add("Url: " + tokens[0] + " --- " + "Localy KeyWord: " + tokens[1]);
}
}
listBox1.DataSource = data;
}
So variable t is the listBox Length(width)
And in this line i tried to calculate and get the text of tokens[1]"
string tt = tokens[1].Substring(t - tokens[1].Length);
But im getting an error startIndex cannot be larger than length of string
Now i know the listBox Length(Width) but i don't want to put the text tokens[1] in a new line only if it's out of the bound out of the listbox Width(Length)
How can i fix and do this ?
Updated again:
Changed the code again now im trying first to check if each line in the variable data lngth is bigger then the variable t:
private void ListBoxLoadKeys(Dictionary<string, List<string>> dictionary, string FileName)
{
int t = listBox1.Width;
using (StreamReader sr = new StreamReader(FileName))
{
while ((line = sr.ReadLine()) != null)
{
int i = line.Count();
tokens = line.Split(',');
dictionary.Add(tokens[0], tokens.Skip(1).ToList());
//string tt = tokens[1].Substring(t - tokens[1].Length);
data.Add("Url: " + tokens[0] + " --- " + "Localy KeyWord: " + tokens[1]);
if (data[i].Length > t)
{
MessageBox.Show("big");
}
}
}
listBox1.DataSource = data;
}
if (data[i].Length > t)
{
MessageBox.Show("big");
}
But im getting an error: Index was out of range. Must be non-negative and less than the size of the collection
You can't do this with a standard listbox. You need to create your own multi line listbox. See this link for some guidance. http://www.codeproject.com/Articles/2695/An-editable-multi-line-listbox-for-NET
I've implemented this at work (ignoring the author's poor choice of colour scheme), and it works fine.

Categories

Resources