I'm creating a web user control in asp.net using C# in which i can select a date from a calendar and display it in a textbox. when i select a date from the calender it has to be displayed in the textbox.
now i need to set my own properties by which i can select datetime patterns in cs codefile. for example
usercontrol1.dd-mm-yyyy.
this is one example. now i want all the datetime patterns of "en-us". when i use that usercontrol in another page i want to set any of the properties(datetime patterns) to that control. please help me!!!
i tried this coding but no use... plz review it and give me solution
public partial class DateControl : System.Web.UI.UserControl
{
string dateformat;
public string Dateformat
{
get { return dateformat;}
set { dateformat = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
PageLoad();
lnlbtnChangeDate.Visible = false;
ddlDateFormat.Visible = false;
Calendar.Visible = false;
}
lblError.Visible = false;
}
public void PageLoad()
{
if (txtBoxDate.Text != "")
{
Calendar.Visible = false;
}
CultureInfo ci = new CultureInfo("fr-fr");
string[] format = ci.DateTimeFormat.GetAllDateTimePatterns();
foreach (string i in format)
{
ddlDateFormat.Items.Add(i);
}
}
protected void lnkbtnPickDate_Click(object sender, EventArgs e)
{
Calendar.Visible = true;
lnlbtnChangeDate.Visible = true;
ddlDateFormat.Visible = false;
}
public void Calendar_SelectionChanged1(object sender, EventArgs e)
{
txtBoxDate.Text = Calendar.SelectedDate.ToShortDateString();
}
protected void ddlDateFormat_SelectedIndexChanged(object sender, EventArgs e)
{
txtBoxDate.Text = Calendar.SelectedDate.ToString(ddlDateFormat.SelectedValue.ToString());
}
protected void lnlbtnChangeDate_Click(object sender, EventArgs e)
{
Calendar.Visible = false;
if (txtBoxDate.Text == "")
{
lblError.Visible = true;
}
else
{
lblError.Visible = false;
lnlbtnChangeDate.Visible = true;
ddlDateFormat.Visible = true;
}
}
protected void lnkbtnClear_Click(object sender, EventArgs e)
{
txtBoxDate.Text = "";
Calendar.Visible = false;
lnlbtnChangeDate.Visible = false;
ddlDateFormat.Visible = false;
lblError.Visible = false;
}
i said that i want set properties for my user control and create events for that.... plz help me
Not sure I get it right at the question is not very clear, but anyway :
You could just create Properties for you user controls, and assign Enums to them
public enum My_UserControl_DateFormats
{
YYYYMMDD = 1,
YYYYMMDDHH = 2,
YYYYMMDDHHmmSS = 3
}
And in the setter code of your properties handle the logic to assign the Date Format (For Example) according to the enum value (using switch/case)
It's one among many possibilities.
Related
I am working on windows form application.
It contains two form MainForm - Test and childForm - Search
Search form has dataGridView control.It contains columns like SrNo, TypeNo, TestEngineer and Date.
And Test form contains textBoxes tb_SerialNo, tb_TypeNo, tb_TestEngineer, datTimePicker for date.
My main Question is when I select Row from datagridview, I want SrNo column value from that row in textbox tb_SerialNo. Same for all.
I wrote following code. But it gives me only SrNo value in tb_SerialNo. but I didn't get TypeNo, TestEnginer and date values in respective textboxes. I am unable to find what i am missing. Please help me to resolve this issue. thanks in advance.
mainForm - Test Code
private void SearchToolStripMenuItem_Click(object sender, EventArgs e)
{
SearchTest Search = new SearchTest(dt);
Search.ShowDialog();
dt.DefaultView.RowFilter = "";
tb_SerialNo.Text = Search.SerialNo;
Search.typeNo = tb_TypeNo.Text;
Search.TestEngineer = tb_TestEngineer.Text;
Search.Date = dateTimePicker1.Text;
}
ChildForm -SearTest Code :
public partial class SearchTest : Form
{
public SearchTest(DataTable TestData)
{
InitializeComponent();
dataGridView1.DataSource = TestData;
this.dataGridView1.Sort(this.dataGridView1.Columns["SrNo"], ListSortDirection.Ascending);
}
private void btn_Search_Click(object sender, EventArgs e)
{
string str = dateTimePicker1.Text;
string str1 = dateTimePicker2.Text;
DateTime date = DateTime.ParseExact(str, "MM/dd/yyyy", CultureInfo.GetCultureInfo("en-GB"));
DateTime date1 = DateTime.ParseExact(str1, "MM/dd/yyyy", CultureInfo.GetCultureInfo("en-GB"));
string dtFilter = string.Format("[Date] >= '{0} ' AND [Date] <= '{1} '", date.ToString("MM/dd/yyyy"), date1.ToString("MM/dd/yyyy"));
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = dtFilter;
}
private void tb_SearchSrNo_TextChanged(object sender, EventArgs e)
{
try
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = String.IsNullOrEmpty(tb_SearchSrNo.Text) ?
"SrNo IS NOT NULL" :
String.Format("SrNo LIKE '{0}%' OR SrNo LIKE '{1}%' OR SrNo LIKE '{2}%'", tb_SearchSrNo.Text, tb_SearchSrNo.Text, tb_SearchSrNo.Text);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void SearchTest_Load(object sender, EventArgs e)
{
groupBox1.Enabled = false;
groupBox3.Enabled = false;
cb_Filter.MouseWheel += new MouseEventHandler(cb_Filter_MouseWheel);
}
private void cb_Filter_SelectedIndexChanged(object sender, EventArgs e)
{
if (cb_Filter.SelectedIndex == 0)
{
groupBox1.Enabled = true;
}
else
{
groupBox3.Enabled = true;
}
}
void cb_Filter_MouseWheel(object sender, MouseEventArgs e)
{
((HandledMouseEventArgs)e).Handled = true;
}
private string SrNo;
private string TypeNo;
private string TestEng;
private string date;
public string SerialNo
{
get { return SrNo; }
set { SrNo = value; }
}
public string typeNo
{
get { return TypeNo; }
set { TypeNo = value; }
}
public string TestEngineer
{
get { return TestEng; }
set { TestEng = value; }
}
public string Date
{
get { return date; }
set { date = value; }
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
SrNo = dataGridView1.CurrentRow.Cells["SrNo"].Value.ToString();
TypeNo = dataGridView1.CurrentRow.Cells["TypeNo"].Value.ToString();
TestEng = dataGridView1.CurrentRow.Cells["TestEngineer"].Value.ToString();
date = dataGridView1.CurrentRow.Cells["Date"].Value.ToString();
}
}
You can change the property definitions to something like this:
public string SomeProperty
{
get
{
string value = null;
if(BindingContext[dataGridView1.DataSource].Current !=null)
{
var r = ((DataRowView)BindingContext[dataGridView1.DataSource].Current).Row;
value = r.Field<string>("SomeDataColumn");
}
return value;
}
}
This way, the SomeProperty will always return the value of SomeDataColumn from the active row.
Try using SelectedRow instead.
The difference between SelectedRow and CurrentRow:
CurrentRow is where the mouse cursor and is selected by the system.
SelectedRow is the row selected in the datagridview and is always selected by the user.
Here's an example code:
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedCells.Count > 0)
{
int index = dataGridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = dataGridView1.Rows[index];
SrNo = selectedRow.Cells["SrNo"].Value.ToString();
TypeNo = selectedRowCells["TypeNo"].Value.ToString();
TestEng = selectedRowCells["TestEngineer"].Value.ToString();
date = selectedRowCells["Date"].Value.ToString();
}
}
I got the answer and my issue is resolved. I found my mistake in mainForm - Test code. I used properties in wrong way for typeNo, TestEngineer and date except for Serial number. Thats why I didn't get values in respective textboxes.
The Corrected MainForm - Test Code:
private void SearchToolStripMenuItem_Click(object sender, EventArgs e)
{
SearchTest Search = new SearchTest(dt);
Search.ShowDialog();
dt.DefaultView.RowFilter = "";
tb_SerialNo.Text = Search.SerialNo;
tb_TypeNo.Text = Search.typeNo;
tb_TestEngineer.Text = Search.TestEngineer;
dateTimePicker1.Text = Search.Date;
}
No need to do any change in Search Form.
I would like to send my Datagridview values to my Combobox in my mainform.
This is my code in my Datagridview form :
private void EquipmentList_Load(object sender, EventArgs e)
{
DataTable.RowCount = 30;
//Beam Description default value
DataTable.Rows[0].Cells[1].Value = "8.000m x 0.400m x 0.550m";
}
Below code is what i've used but nothing happened :
private void MainForm_Load(object sender, EventArgs e)
{
this.KeyPreview = true;
EquipmentList ELform = new EquipmentList();
//Beam Combo Box default values
var BCBi1 = ELform.DataTable.Rows[0].Cells[1].Value.ToString();
this.BeamCB.Items.Add(BCBi1);
}
When i run it i'm getting this error:
error when running
An advance thank you for all those who will help me.
DataTable.Rows[0].Cells[1].Value is assigned in EquipmentList form when it is loaded.
EquipmentList ELform = new EquipmentList(); - here form is created but not loaded (you need to invoke Show or ShowDialog for that).
I suggest to declare publicly accessible default value (and not rely on existance of DataTable object with 1 row, which is a low-level implementation detail)
public const string DefaultSize = "8.000m x 0.400m x 0.550m";
private void EquipmentList_Load(object sender, EventArgs e)
{
DataTable.RowCount = 30;
DataTable.Rows[0].Cells[1].Value = DefaultSize;
}
and then
private void MainForm_Load(object sender, EventArgs e)
{
this.KeyPreview = true;
this.BeamCB.Items.Add(EquipmentList.DefaultSize);
}
To the question "So is there any possible to load that values wihtout clicking/showing my equipmentlist form." Absolutely. Start by building a class for your data:
public class gridviewdata
{
public string content { get; set; }
public int row { get; set; }
public int cell { get; set; }
public gridviewdata(string content, int row, int cell)
{
this.content = content;
this.row = row;
this.cell = cell;
}
}
add a mediator class:
public static class mediator
{
public static List<gridviewdata> gridviewdatalist;
}
then add this code to your ELform load event:
private void EquipmentList_Load(object sender, EventArgs e)
{
DataTable.RowCount = 30;
//Beam Description default value
DataTable.Rows[0].Cells[1].Value = "8.000m x 0.400m x 0.550m";
mediator.gridviewdatalist.Add(new gridviewdata("8.000m x 0.400m x 0.550m", 0, 1);
}
then add a new method identifying your specific row to your MainForm:
private gridviewdata selectdata(int row, int cell)
{
foreach(gridviewdata data in mediator.gridviewdatalist)
{
if(data.row == row && data.cell == cell)
{
return data;
}
}
return null;
}
And finally call that code in your MainForm:
private void MainForm_Load(object sender, EventArgs e)
{
this.KeyPreview = true;
//and call it there
var BCBi1 = selectdata(0, 1);
this.BeamCB.Items.Add(new Item(BCDi1, 1)); //Add value and index
}
Hope this helps.
I need make Button active if theese three bools are true
public bool isFileOpened = false;
public bool isDrive = false;
public bool isPrice = false;
They are becoming true after two textboxes are filled and
filePath string is not empty
private void textBox1_TextChanged(object sender, EventArgs e) {
drive = CheckIntInput(sender, "not valid");
if (drive != 0) {
isDrive = true;
}
}
private void textBox2_TextChanged(object sender, EventArgs e) {
price = CheckIntInput(sender, "not valid");
if (price != 0) {
isPrice = true;
}
}
private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e) {
filePath = openFileDialog1.FileName;
label1.Text = filePath;
isFileOpened = true;
}
CheckIntInput method returning number from textBox or 0 if can`t convert string to number
And how i can make something like this:
if (isFileOpened && isDrive && isPrice) {
showButton.Enabled = true;
}
I want to make button enabled immediately after all three bools becomes true, and theese three fields can be inputted in different ways, like
textbox1
textbox2
openfiledialog1
or
textbox1
openfiledialog1
textbox2
There are multiple ways to do this, I'd use a property with a backing field, like this:
public bool IsFileOpened
{
get { return _isFileOpened; }
set
{
_isFileOpened = value;
UpdateShowButton();
}
}
public bool IsDrive
{
get { return _isDrive; }
set
{
_isDrive = value;
UpdateShowButton();
}
}
public bool IsPrice
{
get { return _isPrice; }
set
{
_isPrice = value;
UpdateShowButton();
}
}
private void UpdateShowButton()
{
if (IsPrice && IsDrive && IsFileOpened)
showButton.Enabled = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
drive = CheckIntInput(sender, "not valid");
if (drive != 0)
{
IsDrive = true;
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
price = CheckIntInput(sender, "not valid");
if (price != 0)
{
IsPrice = true;
}
}
private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
filePath = openFileDialog1.FileName;
label1.Text = filePath;
IsFileOpened = true;
}
Actually I renamed it as well, so you have to use the properties with the capitalized starting letter. Now, everytime a property is updated, it checks wether to set the showButton enabled or not.
Here you can read more about fields and properties (with backing fields as well).
I have made a simple TO-DOs program that gets input from a text box then place it in another text box. With tick boxes next to it,
this is all fine except i Cannot save the list eg. the item and if it's finished or not.
Please could anyone help me be able to save this list of items.
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;
namespace TO_DOs
{
public partial class Form1 : Form
{
private bool text1, text2, text3, text4, text5, text6, text7, text8;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (text1 == false)
{
textBox2.Text = textBox1.Text;
}
else if (text2 == false)
{
textBox3.Text = textBox1.Text;
}
else if (text3 == false)
{
textBox4.Text = textBox1.Text;
}
else if (text4 == false)
{
textBox5.Text = textBox1.Text;
}
else if (text5 == false)
{
textBox6.Text = textBox1.Text;
}
else if (text6 == false)
{
textBox7.Text = textBox1.Text;
}
else if (text7 == false)
{
textBox8.Text = textBox1.Text;
}
else if (text8 == false)
{
textBox9.Text = textBox1.Text;
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
text1 = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
text2 = true;
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
text3 = true;
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
text4 = true;
}
private void textBox6_TextChanged(object sender, EventArgs e)
{
text5 = true;
}
private void textBox7_TextChanged(object sender, EventArgs e)
{
text6 = true;
}
private void textBox8_TextChanged(object sender, EventArgs e)
{
text7 = true;
}
private void textBox9_TextChanged(object sender, EventArgs e)
{
text8 = true;
}
}
}
I would do it like this:
Create a class to store your values in:
public class ListEntry
{
public string Text { get; set; }
public bool Finished { get; set; }
}
Then I would create 2 Methods:
public List<ListEntry> UI_To_List(); //Create UI from your saved file
public void List_To_UI(List<ListEntry> entries); //Process your UI
Now it's your choice on how to store your list.
You could store it as JSON or XML.
A few recommendations:
I would create a UserControl for your TextBox + CheckBox
Display the 'List of UserControls' in a FlowLayoutPanel
=> then you can process the FlowLayoutPanel.Controls List.
This will make your List dynamically size to an 'unlimited' amount of items.
Short example:
Create a UserControl (Rightclick project for that):
Add these 2 methods to the code of your UserControl (F7 / rightclick => View Code):
public void SetText(string text)
{
//Set the Text of your TextBox in the UserControl:
textBox1.Text = text;
}
public void SetFinished(bool finished)
{
//Set the Checked of your CheckBox in the UserControl:
checkBox1.Checked = finished;
}
In your MainForm add an FlowLayoutPanel (from ToolBox).
Add your Data like this (using class from above):
/// <summary>
///
/// </summary>
/// <param name="entries">You will get them from loading your previously saved file</param>
public void CreateUI(List<ListEntry> entries)
{
foreach (ListEntry entry in entries)
{
//Create new instance of your UserControl
TaskView view = new TaskView();
view.SetFinished(entry.IsFinished);
view.SetText(entry.Text);
//Add that to your UI:
this.flowLayoutPanel1.Controls.Add(view);
}
}
The result will look like this:
I'm not sure what exactly it is that you want to save in a list... but here's just a tip when checking conditions, instead of using if (text1 == false), simply do if (!text1) as this means "is not true" because by default if (text1) will return true.
private void button1_Click(object sender, EventArgs e)
{
if (!text1)
{
textBox2.Text = textBox1.Text;
}
else if (!text2)
{
textBox3.Text = textBox1.Text;
}
// Left out the rest of the else ifs
}
You are casting textboxes wrong. For example when you change textBox4, you gave text3 true.
private void textBox4_TextChanged(object sender, EventArgs e)
{
text3 = true;
}
Then you cast
TextBox4.Text = TextBox1.Text;
It changes TextBox4.Text to TextBox1.Text.
You probably want to save TextBox4.Text here at TextBox1.Text so you sould change all if blocks like that. So you have to give only one "true" function for changed textBox sign and change if blocks
if(text(boolNum))
TextBox1.Text = TextBox(Number).Text;
Just swap them and try like that.
If you want to save another thing by another way. You have to be more spesific.
You can use a CheckedListbox to hold all tot actions.
You can then tick the itemsand for instance in the OK button you include a save action:
foreach(var item in MyCheckedListbox.CheckedItems)
{
Console,WriteLine(item.Text);
}
Lets see the answer from Felix D. He tells you exactly how to create a class and save the items into it. But now you only have a List that will be available as long as your software is running. You still need to save it somewhere on your desktop.
Lucky for you, you got a really simple pattern.
string; boolean
So how about you make it yourself simple? Just create a textfile and write your entries, as example in a csv marked with a ; for every information?
Example:
class Program
{
public class tmpClass
{
public string Text;
public bool tick;
}
public List<tmpClass> tmpList = new List<tmpClass>();
static void Main(string[] args)
{
//Stuff
}
public void WriteToFile()
{
string tmpTextFilePath = #"C:\User\Desktop\SaveText.txt";
using (StreamWriter tmpWriter = new StreamWriter(tmpTextFilePath))
{
string tmpTextToWrite = String.Empty;
for (int i = 0; i < tmpList.Count; i++)
{
tmpClass tmpEntry = tmpList[i];
tmpTextToWrite += tmpEntry.Text + ";" + tmpEntry.tick;
}
tmpWriter.WriteLine(tmpTextToWrite);
}
//Now we wrote a text file to you desktop with all Informations
}
public void ReadFromFile()
{
string tmpTextFilePath = #"C:\User\Desktop\SaveText.txt";
using (StreamReader tmpReader = new StreamReader(tmpTextFilePath))
{
string tmpText = tmpReader.ReadLine();
string tmpInput = String.Empty;
tmpClass tmpClass = new tmpClass();
int i = 0;
foreach (char item in tmpText)
{
if(item.Equals(";".ToCharArray()))
{
if (i == 0)
{
tmpClass.Text = tmpInput;
i = 1;
tmpInput = String.Empty;
}
else
{
if (tmpInput == "True")
tmpClass.tick = true;
else
tmpClass.tick = false;
i = 0;
tmpInput = String.Empty;
tmpList.Add(tmpClass);
}
}
tmpInput += item;
}
}
}
}
This should simply write a txt File to your desktop with your information and read one and save it to your list.
I have this simple code in my DevExpress LookUp control (should be identical with a normal combobox)
private void lookUpUsers_EditValueChanged(object sender, EventArgs e)
{
lookUpRolesPréÉdit.EditValue = null;
}
private void lookUpRolesPréÉdit_EditValueChanged(object sender, EventArgs e)
{
lookUpUsers.EditValue = null;
}
The problem is that when I select a value in lookUpUsers, is resets the other lookup which then resets lookUpUsers. So when I pick a value, both combobox become null. What I want is that when you pick a value in combobox 1, combobox 2 resets its value.
How about this:
private void lookUpUsers_EditValueChanged(object sender, EventArgs e)
{
if(lookUpUsers.EditValue != null)
lookUpRolesPréÉdit.EditValue = null;
}
private void lookUpRolesPréÉdit_EditValueChanged(object sender, EventArgs e)
{
if(lookUpRolesPréÉdit.EditValue != null)
lookUpUsers.EditValue = null;
}
There might be an easier way than this, as my knowledge of C# is limited (especially their libraries like you are using them here). Nevertheless, this is an answer that uses no magic provided by libraries:
private bool localEdit = false;
private void lookUpUsers_EditValueChanged(object sender, EventArgs e)
{
if (!localEdit)
{
localEdit = true;
lookUpRolesPréÉdit.EditValue = null;
localEdit = false;
}
}
private void lookUpRolesPréÉdit_EditValueChanged(object sender, EventArgs e)
{
if (!localEdit)
{
localEdit = true;
lookUpUsers.EditValue = null;
localEdit = false;
}
}
Here's a solution I've come up with
private void lookUpUsers_EditValueChanged(object sender, EventArgs e)
{
if (!isEditFinished)
{
isEditFinished = true;
lookUpRolesPréÉdit.EditValue = null;
}
isEditFinished = false;
}
private void lookUpRolesPréÉdit_EditValueChanged(object sender, EventArgs e)
{
if (!isEditFinished)
{
isEditFinished = true;
lookUpUsers.EditValue = null;
}
isEditFinished = false;
}