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
{ ...
Related
I'll try to add as much information as needed, please tell me if you need any extra info that I haven't added and I'll do my best to provide it.
The basics of my problem is that whenenver I press a button, it will grab the file I select and save it to a text file. This works fine and I can save as many files as needed. The problem lies in the listbox of my listbox. My app is a soundboard, and I want filenames with their hotkeys to be displayed on the listbox which almost works fine. On loading the application the listbox will take all saved files and display them accordingly once and on adding a file, the file will be added to the listbox and it will be saved. As I said this almost works because for some reason unknown to me, you have to click the listbox for it to add the content. My code is as follows:
public partial class Form1 : Form
{
public int getNumberOfSongs()
{
using (Stream stream = File.Open(#"Sounds.txt", FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
string line = null;
for (int i = 0; i < 1; ++i)
{
line = reader.ReadLine();
int ine = Int32.Parse(line);
ine = ine + 1;
return ine;
}
}
}
return 8;
//This is only here so it doesn't give me an error, it is never used
}
public void fineChanger(string newText, string fileName, int line_to_edit)
{
string[] arrLine = File.ReadAllLines(fileName);
arrLine[line_to_edit] = newText;
File.WriteAllLines(fileName, arrLine);
}
public void addFile()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "WAV files (*.wav)|*.wav";
openFileDialog.DefaultExt = ".wav";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
string filePath = openFileDialog.FileName;
songToAdd = filePath;
string control = filePath + "§modifier§hotkey";
string savePath = #"Sounds.txt";
int bruh = getNumberOfSongs();
fineChanger(control, savePath, bruh);
string bru = bruh.ToString();
fineChanger(bru, savePath, 0);
add = true;
}
}
public bool add = false;
public string songToAdd;
public bool load = true;
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
addFile();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (load == true)
{
listBox1.DataSource = File.ReadAllLines(#"Sounds.txt");
load = false;
}
if(add == true)
{
listBox1.Items.Add(songToAdd);
add = false;
}
}
}
P.S. I'm still a novice at windows forms and this app is still nowhere near done.
Instead of adding the items in SelectedIndexChanged I added them in outside. I load the saved songs in Form1_Load and I open/save the loaded files in the addFile() function.
Edited Code:
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.Media;
using System.Security.Cryptography.X509Certificates;
using System.Runtime;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic;
using System.Diagnostics;
namespace SoundBoard
{
public partial class Form1 : Form
{
public int getNumberOfSongs()
{
using (Stream stream = File.Open(#"Sounds.txt", FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
string line = null;
for (int i = 0; i < 1; ++i)
{
line = reader.ReadLine();
int ine = Int32.Parse(line);
ine = ine + 1;
return ine;
}
}
}
return 8;
//This is only here so it doesn't give me an error, it is never used
}
public bool load = true;
public void fineChanger(string newText, string fileName, int line_to_edit)
{
string[] arrLine = File.ReadAllLines(fileName);
arrLine[line_to_edit] = newText;
File.WriteAllLines(fileName, arrLine);
}
public void addFile()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "WAV files (*.wav)|*.wav";
openFileDialog.DefaultExt = ".wav";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
string filePath = openFileDialog.FileName;
string control = filePath + "§modifier§hotkey";
string savePath = #"Sounds.txt";
int bruh = getNumberOfSongs();
fineChanger(control, savePath, bruh);
string bru = bruh.ToString();
fineChanger(bru, savePath, 0);
listBox1.Items.Add(filePath);
}
}
public bool loada = true;
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
addFile();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
if (loada == true)
{
listBox1.Items.Add(File.ReadAllLines(#"Sounds.txt"));
loada = false;
}
}
}
}
Every time when I click the button only one row will be displayed. But it should show multiple rows. I declare the list after the constructor invoke. I tried with gridview.update() and gridview.refresh() but they didn't work. I could not findout the issue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using JournalEntryApp.Model;
namespace JournalEntryApp
{
public partial class NewDocument : Form
{
public NewDocument()
{
InitializeComponent();
}
List<JEFrom> JEFromsList = new List<JEFrom>();
List<JETo> JETosList = new List<JETo>();
JEFrom _jef = null;
private void NewDocument_Load(object sender, EventArgs e)
{
label4.Text = DateTime.Now.ToString("dd-MMM-yyyy");
using (var db =new JournalContext())
{
unitComboBox.DataSource = db.Units.ToList();
unitComboBox.ValueMember = "Id";
unitComboBox.DisplayMember = "UnitName";
}
}
private void addToListButton_Click(object sender, EventArgs e)
{
if (string.Empty== fromAccountTextBox.Text)
{
MessageBox.Show("From Account can not be empty!!!");
}
else if (string.Empty == toAccountTextBox.Text)
{
MessageBox.Show("To Account can not be empty!!!");
}
else
{
_jef = new JEFrom{ FromEntryName= fromAccountTextBox.Text , FromEntryDate= DateTime.Now };
JEFromsList.Add(_jef);
temporaryDataGridView.DataSource = JEFromsList;
fromAccountTextBox.Text = string.Empty;
toAccountTextBox.Text = string.Empty;
}
}
}
}
The temporaryDataGridView cannot detect that you have changed the DataSource. It will only refresh when Datasource has changed.
temporaryDataGridView.DataSource = null;
temporaryDataGridView.DataSource = JEFromsList;
so change the Datasource null first.
Or you can use bindingSource
private void NewDocument_Load(object sender, EventArgs e)
{
this.bindingSource1.DataSource = JEFromsList;
temporaryDataGridView.DataSource = this.bindingSource1;
label4.Text = DateTime.Now.ToString("dd-MMM-yyyy");
using (var db =new JournalContext())
{
unitComboBox.DataSource = db.Units.ToList();
unitComboBox.ValueMember = "Id";
unitComboBox.DisplayMember = "UnitName";
}
}
in button_click
JEFromsList.Add(_jef);
bindingSource1.ResetBindings(true);
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
}
I’m trying to create a webpage that displays dynamically placed WebUserControls depending on a question type that is returned from and SQL server. When you press a button on the usercontrols it checks the result from the usercontrol using the procedure “CheckResult”. For some reason when you click on the buttons within the usercontrols ("cmdProcess") the Event “CheckResult” does not fire. What am I doing wrong please?
The User control code is: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Testing.Event_Delegate
{
public partial class WebUserControl2 : System.Web.UI.UserControl
{
// Delegate declaration
public delegate void PhotoUploaded(string strFilename, String FailureMessage, string strFabricationNo, string strPartNo, string strBatchNo, string strPartSN, string strSTK_SerialNo, string strSTK_PartNo);
// Event declaration
public event PhotoUploaded Resultresponse;
string questionAsked;
public string QuestionText
{
set { questionAsked = value; }
get { return questionAsked; }
}
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = QuestionText;
TextBox1.Focus();
}
protected void cmdProcess_Click(object sender, EventArgs e)
{
if (Resultresponse != null)
{
Resultresponse("Passed", "", "", "", "", "", "", "");
}
TextBox1.Text = "";
}
}
}
And the main ASPX page that the usercontrols are placed on is: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Testing.Event_Delegate
{
public partial class WebForm1 : System.Web.UI.Page
{
WebUserControl2 QT2;
WebUserControl3 QT3;
DataTable dtQuestionSet;
protected void Page_Load(object sender, EventArgs e)
{
// all controls need to be rendered every page postback otherwise the rest of the code loses scope.
QT2 = (WebUserControl2)this.LoadControl("WebUserControl2.ascx");
QT3 = (WebUserControl3)this.LoadControl("WebUserControl3.ascx");
if (IsPostBack == false)
{
Session["Counter"] = 0;
Session["QuestionCount"] = 0;
Session["CompletedInsp"] = false;
Session["RunInsp"] = false;
dtQuestionSet = new DataTable();
MakeDataTabledtQuestionSet();
}
else
{
dtQuestionSet = (DataTable)Session["DataTableW"];
//check to see if the inspection process is complete and display pass\fail and log. Else carry on.
if (Convert.ToBoolean(Session["CompletedInsp"]) == true)
{
//Response.Write("Failed");
ModalPopupExtender2.Show();
return;
}
}
Session["DataTableW"] = dtQuestionSet;
}
void CheckResult(string Result, string FailureMessage, string FabricationNo, string PartNo, string BatchNo, string PartSN, string STK_SerialNo, string STK_PartNo)
{
Label1.Text = "You Answered: - " + Result;
if ((Convert.ToInt32(Session["Counter"]))>= Convert.ToInt32(Session["QuestionCount"]))
{
Session["CompletedInsp"] = true;
Session["RunInsp"] = false;
}
else
{
dtQuestionSet = (DataTable)Session["DataTableW"];
}
Session["Counter"] = Convert.ToInt32(Session["Counter"]) + 1;
//If the inspection hasn't been completed carry on and ask next question.
if (Convert.ToBoolean(Session["RunInsp"]) == true)
{
RunInspection();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("WebForm1.aspx");
}
protected void cmdStartInspection_Click(object sender, EventArgs e)
{
Session["Counter"] = 0;
GetQuestions();
}
protected void GetQuestions()
{
dtQuestionSet.Clear();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PromptedInspConnectionString"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("test.GetQuestions", conn);
SqlDataReader dr = null;
cmd.CommandType = CommandType.StoredProcedure;
dr = cmd.ExecuteReader();
while (dr.Read())
{
DataRow drQuestions = dtQuestionSet.NewRow();
drQuestions["QuestionText"] = dr[1].ToString();
drQuestions["ExpectedResponse"] = dr[2].ToString();
drQuestions["QuestionType"] = dr[3].ToString();
dtQuestionSet.Rows.Add(drQuestions);
}
Session["DataTableW"] = dtQuestionSet;
Session["QuestionCount"] = dtQuestionSet.Rows.Count;
conn.Close();
RunInspection();
Session["RunInsp"] = true;
}
protected void RunInspection()
{
//Populate the user controls
switch (dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][2].ToString())
{
case "1":
QT2.QuestionText = dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][0].ToString();
QT2.Resultresponse += new WebUserControl2.PhotoUploaded(CheckResult);
break;
case "2":
QT3.QuestionText = dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][0].ToString();
QT3.Resultresponse += new WebUserControl3.PhotoUploaded(CheckResult);
break;
}
//Add the usercontrols to the form
PlaceHolder2.Controls.Add(QT2);
PlaceHolder2.Controls.Add(QT3);
//Need to set the visability of the usercontrol so it only shows the usercontrol that is displaying the question
QT2.Visible = false;
QT3.Visible = false;
switch (dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][2].ToString())
{
case "1":
QT2.Visible = true;
break;
case "2":
QT3.Visible = true;
break;
}
}
private void MakeDataTabledtQuestionSet()
{
dtQuestionSet.Columns.Add("QuestionText");
dtQuestionSet.Columns.Add("ExpectedResponse");
dtQuestionSet.Columns.Add("QuestionType");
}
}
}
Try initializing the controls in OnPreInit rather than load. Controls binding is done in OnPreInit.
See the page lifecyle events MSDN Reference
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.