I am working on a project (simple phone book) for personal use. This is how it looks like:
I have a listview filled with contacts and everything was working perfectly untill I added this line of code, when everything became messed up.
listView1.Sorting = SortOrder.Ascending;
So, the problem is obvious. Let's say that there are 6 contacts in the list, and Contact 1 lives in City 1, on Address 1, has a Tel. No 1 [etc], and Contact 2 lives in City 2, on Address 2, has a Tel. No 2 etc. [...sequence continues...]
When I try to make some changes, for example, Contact 5 suddenly gets the information of other contact, in this case, Contact 7. It doesn't matter whose information it gets though, the matter is that everything becomes messed up.
Also, if i want to delete all the contacts from the listview - it is not possible - there will always be one remaining. For example, if there were 6 of them, 5 would be deleted and there would be one left. Also, if there was 100 of them, it would delete 99 and the one would always remain as well.
I figured out that there is no sense to use index of selected item anymore and that I have to use value of the selected item now (instead of its index). But, the problem is I do not know how to do that.
Maybe it comes to listView1_SelectedIndexChanged only. Please note that i am just taking a guess, I am not completely sure.
If so, here is the code:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count == 0) return;
textBox1.Text = people[listView1.SelectedItems[0].Index].Name;
textBox2.Text = people[listView1.SelectedItems[0].Index].Hometown;
textBox3.Text = people[listView1.SelectedItems[0].Index].Address;
textBox4.Text = people[listView1.SelectedItems[0].Index].Phone;
textBox5.Text = people[listView1.SelectedItems[0].Index].Email;
textBox6.Text = people[listView1.SelectedItems[0].Index].AdditionalInfo;
dateTimePicker1.Value = people[listView1.SelectedItems[0].Index].Birthday;
textBox1.ReadOnly = true;
textBox2.ReadOnly = true;
textBox3.ReadOnly = true;
textBox4.ReadOnly = true;
textBox5.ReadOnly = true;
textBox6.ReadOnly = true;
dateTimePicker1.Enabled = false;
toolStripButton5.Enabled = true;
}
I think the code is to big to upload it here, so I uploaded the code here:
Does anyone have a solution?
In order to find the right object to update you first need to find the object in the People collection that matches the object selected in the ListView.
Person i = People.FirstOrDefault(p => p.Name == ((ListView) sender).SelectedItems[0].Text);
PopulateEditData(i); // refer below for method...
This can only work if you have the MultiSelect property set to false, otherwise you will need to get the right item from the collection of selected items.
As seen here: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.selecteditems(v=vs.110).aspx
Once you have the right Person object, you will be able to retrieve and display the objects details in the text boxes:
private void PopulateEditData(Person selectedPerson)
{
textBox1.Text = selectedPerson.Name;
textBox2.Text = selectedPerson.Hometown;
textBox3.Text = selectedPerson.Address;
textBox4.Text = selectedPerson.Phone;
textBox5.Text = selectedPerson.Email;
textBox6.Text = selectedPerson.AdditionalInfo;
dateTimePicker1.Value = selectedPerson.Birthday;
textBox1.ReadOnly = true;
textBox2.ReadOnly = true;
textBox3.ReadOnly = true;
textBox4.ReadOnly = true;
textBox5.ReadOnly = true;
textBox6.ReadOnly = true;
dateTimePicker1.Enabled = false;
toolStripButton5.Enabled = true;
}
I would also suggest setting the selectPerson as a property of your form or one of the classes available to it so it is a little easier to edit and save the data on the object.
For the removal part of the problem, use the SelectedPerson property for the item to be removed.
private void button1_Click(object sender, EventArgs e)
{
if (SelectedPerson != null)
{
People.Remove(SelectedPerson);
this.listView1.Items.Clear();
foreach (var person in People)
{
this.listView1.Items.Add(person.ToString());
this.listView1.Sorting = SortOrder.Ascending;
}
this.listView1.Refresh();
this.button1.Enabled = false;
}
}
Thank you for your answer.
Anyway, I have managed to solve the problem in the following way:
1) I have added:
private Person FindPerson(string name)
{
return people.Find(x => x.Name == name);
}
2) I have replaced:
people[listView1.SelectedItems[0].Index]
with "person", where person is:
Person person = FindPerson(listView1.SelectedItems[0].Text);
where FindPerson is:
private Person FindPerson(string name)
{
return people.Find(x => x.Name == name);
}
Anyway, I keep getting error when I try to remove the last remaining contact. Even when I try to select it, not just remove it. Here you can take a look what error is about:
IMAGE: http://s24.postimg.org/ls4nak6et/Kruzeri.png
So, this is how it looks like now:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count == 0) return;
Person person = FindPerson(listView1.SelectedItems[0].Text);
textBox1.Text = person.Name;
textBox2.Text = person.Hometown;
textBox3.Text = person.Address;
textBox4.Text = person.Phone;
textBox5.Text = person.Email;
textBox6.Text = person.AdditionalInfo;
dateTimePicker1.Value = person.Birthday;
textBox1.ReadOnly = true;
textBox2.ReadOnly = true;
textBox3.ReadOnly = true;
textBox4.ReadOnly = true;
textBox5.ReadOnly = true;
textBox6.ReadOnly = true;
dateTimePicker1.Enabled = false;
toolStripButton5.Enabled = true;
}
and Save button:
private void toolStripButton1_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
Person person = FindPerson(listView1.SelectedItems[0].Text);
person.Name = textBox1.Text;
person.Hometown = textBox2.Text;
person.Address = textBox3.Text;
person.Phone = textBox4.Text;
person.Email = textBox5.Text;
person.Birthday = dateTimePicker1.Value;
person.AdditionalInfo = textBox6.Text;
listView1.SelectedItems[0].Text = textBox1.Text;
textBox1.ReadOnly = true;
textBox2.ReadOnly = true;
textBox3.ReadOnly = true;
textBox4.ReadOnly = true;
textBox5.ReadOnly = true;
textBox6.ReadOnly = true;
dateTimePicker1.Enabled = false;
}
else
{
MessageBox.Show("Nothing is selected ", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
UserCount();
}
Your function returns null because no item is selected. So person is of course null. You should handle this in your FindPerson-Function.
Related
I need some help getting my code to work. DataGridView is proving much more complex that I had anticipated. I need someone to please show me how to fix my code, so that both the DataGridView control can be updated and my DataGridViewComboBoxColumn dropdown and DataGridViewCheckBoxColumn controls all work. I'm okay with any strategy, provided the solution you offer is somewhat elegant and complete. I've already spent far too much time trying to figure this out on my own. Any thoughts or suggestions would be greatly appreciated.
Here is a simplifcation of what my backend looks like:
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(sqlRequestString, this.dbConnection);
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource.DataSource = table;
If I get rid of the BindingSource, how do I connect the DataTable directly to the DataGridView, so that the ComboBox and Checkbox columns are properly populated?
UPDATE
This should be a complete overview of how I am attempting to initialize my DataGridView:
private void InitializeComponent()
{
/* ... */
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.DataGridViewColumn_Section,
this.DataGridViewColumn_Indent,
this.DataGridViewColumn_Content,
this.DataGridViewColumn_Summary,
this.DataGridViewColumn_Role,
this.DataGridViewColumn_Author,
this.DataGridViewColumn_Updated});
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.DataSourceChanged += new System.EventHandler(this.dataGridView1_DataSourceChanged);
this.dataGridView1.CellEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellEnter);
this.dataGridView1.CellLeave += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellLeave);
this.dataGridView1.ColumnAdded += new System.Windows.Forms.DataGridViewColumnEventHandler(this.dataGridView1_ColumnAdded);
this.dataGridView1.SelectionChanged += new System.EventHandler(this.dataGridView1_SelectionChanged);
this.dataGridView1.Leave += new System.EventHandler(this.dataGridView1_Leave);
//
// DataGridViewColumn_Section
//
this.DataGridViewColumn_Section.HeaderText = "Section";
this.DataGridViewColumn_Section.Name = "DataGridViewColumn_Section";
//
// DataGridViewColumn_Indent
//
this.DataGridViewColumn_Indent.HeaderText = "Indent";
this.DataGridViewColumn_Indent.Name = "DataGridViewColumn_Indent";
//
// DataGridViewColumn_Content
//
this.DataGridViewColumn_Content.HeaderText = "Content";
this.DataGridViewColumn_Content.MinimumWidth = 100;
this.DataGridViewColumn_Content.Name = "DataGridViewColumn_Content";
//
// DataGridViewColumn_Summary
//
this.DataGridViewColumn_Summary.HeaderText = "Summary";
this.DataGridViewColumn_Summary.Name = "DataGridViewColumn_Summary";
//
// DataGridViewColumn_Role
//
this.DataGridViewColumn_Role.HeaderText = "Minimum Signoff";
this.DataGridViewColumn_Role.Name = "DataGridViewColumn_Role";
//
// DataGridViewColumn_Author
//
this.DataGridViewColumn_Author.HeaderText = "Author";
this.DataGridViewColumn_Author.Name = "DataGridViewColumn_Author";
this.DataGridViewColumn_Author.ReadOnly = true;
//
// DataGridViewColumn_Updated
//
this.DataGridViewColumn_Updated.HeaderText = "Updated";
this.DataGridViewColumn_Updated.Name = "DataGridViewColumn_Updated";
this.DataGridViewColumn_Updated.ReadOnly = true;
/* ... */
}
public MyWinform()
{
InitializeComponent();
// Initialize DataGridView DataTable
this.dgvDataTable = new DataTable();
// Initialize DataGridView column indexes
this.idxSection = dataGridView1.Columns["DataGridViewColumn_Section"].Index;
this.idxIndent = dataGridView1.Columns["DataGridViewColumn_Indent"].Index;
this.idxContent = dataGridView1.Columns["DataGridViewColumn_Content"].Index;
this.idxSummary = dataGridView1.Columns["DataGridViewColumn_Summary"].Index;
this.idxRole = dataGridView1.Columns["DataGridViewColumn_Role"].Index;
this.idxAuthor = dataGridView1.Columns["DataGridViewColumn_Author"].Index;
this.idxLastUpdate = dataGridView1.Columns["DataGridViewColumn_Updated"].Index;
}
private void MyWinform_Load(object sender, EventArgs e)
{
DataGridView dgv = this.dataGridView1;
DataGridViewComboBoxColumn comboCol;
// Load System Menu
SystemMenu.Load(this.Handle);
// Insert selection prompt
ProcTemplateRecord selectProcPrompt = new ProcTemplateRecord();
selectProcPrompt.PrimaryKey = 0;
selectProcPrompt.ProcName = "Select from the list...";
this.procList.Insert(0, selectProcPrompt);
// Add new procedure prompt
ProcTemplateRecord newProcPrompt = new ProcTemplateRecord();
newProcPrompt.PrimaryKey = -1;
newProcPrompt.ProcName = "Start a new Safe Job Procedure";
this.procList.Add(newProcPrompt);
// Finish initializing the ComboBox dropdown list
this.comboBox1.DataSource = this.procList;
this.comboBox1.DisplayMember = "ProcName";
this.comboBox1.ValueMember = "PrimaryKey";
// Finish initializing DataGridView and bind to BindingSource
this.dataGridView1.AutoGenerateColumns = false;
/*
// Finish initializing the DataGridView ComboBox columns...
comboCol = (DataGridViewComboBoxColumn)dgv.Columns[this.idxSection];
comboCol.DataSource = Enum.GetValues(typeof(SectionType));
comboCol.ValueType = typeof(SectionType);
comboCol.DropDownWidth = ComboBoxMaxLabelWidth(comboCol);
comboCol = (DataGridViewComboBoxColumn)dgv.Columns[this.idxRole];
comboCol.DataSource = Enum.GetValues(typeof(RoleType));
comboCol.ValueType = typeof(RoleType);
comboCol.DropDownWidth = ComboBoxMaxLabelWidth(comboCol);
this.dataGridView1.DataSource = this.dgvDataTable;
*/
this.RefreshDataGridViewColumnWidths();
// Setup post-initialization DataGridViewEvent handlers
this.dataGridView1.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
this.dataGridView1.CurrentCellDirtyStateChanged += new System.EventHandler(this.dataGridView1_CurrentCellDirtyStateChanged);
}
private void dataGridView1_DataSourceChanged(object sender, EventArgs e)
{
this.RefreshDataGridViewColumnWidths();
}
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
this.RefreshButtons();
if (e.ColumnIndex == this.idxSection)
{
this.label_dgvToolTip.Visible = false;
}
else if (e.ColumnIndex == this.idxIndent)
{
this.label_dgvToolTip.Visible = false;
}
else if (e.ColumnIndex == this.idxContent)
{
this.label_dgvToolTip.Visible = false;
}
else if (e.ColumnIndex == this.idxSummary)
{
this.label_dgvToolTip.Visible = false;
}
else if (e.ColumnIndex == this.idxRole)
{
this.label_dgvToolTip.Visible = false;
}
else if (e.ColumnIndex == this.idxAuthor)
{
this.label_dgvToolTip.Visible = false;
this.label_dgvToolTip.Text = "Author column values are read only.";
this.label_dgvToolTip.Visible = true;
}
else if (e.ColumnIndex == this.idxLastUpdate)
{
this.label_dgvToolTip.Visible = false;
this.label_dgvToolTip.Text = "Updated column values are read only.";
this.label_dgvToolTip.Visible = true;
}
else
{
this.label_dgvToolTip.Visible = false;
}
this.idxActiveColumn = e.ColumnIndex;
this.idxActiveRow = e.RowIndex;
}
private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
this.label_dgvToolTip.Visible = false;
this.RefreshButtons();
}
private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
DataGridView dgv = this.dataGridView1;
if ((e.Column.DataPropertyName == "PageSection") &&
(e.Column.CellType != typeof(DataGridViewComboBoxCell)))
{
var cbo = GetComboBoxColumn(e.Column);
cbo.DataSource = Enum.GetValues(typeof(SectionType));
cbo.ValueType = typeof(SectionType);
dgv.Columns.Remove(e.Column);
dgv.Columns.Add(cbo);
}
else if ((e.Column.DataPropertyName == "UserRole") &&
(e.Column.CellType != typeof(DataGridViewComboBoxCell)))
{
var cbo = GetComboBoxColumn(e.Column);
cbo.DataSource = Enum.GetValues(typeof(RoleType));
cbo.ValueType = typeof(RoleType);
dgv.Columns.Remove(e.Column);
dgv.Columns.Add(cbo);
}
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
this.RefreshButtons();
}
private void dataGridView1_Leave(object sender, EventArgs e)
{
DataGridView dgv = this.dataGridView1;
if (dgv.SelectedCells.Count == 0)
{
this.idxActiveColumn = -1;
this.idxActiveRow = -1;
}
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
DataGridViewComboBoxCell sectionCell = (DataGridViewComboBoxCell)dgv.Rows[e.RowIndex].Cells[this.idxSection];
DataGridViewTextBoxCell indentCell = (DataGridViewTextBoxCell)dgv.Rows[e.RowIndex].Cells[this.idxIndent];
DataGridViewComboBoxCell roleCell = (DataGridViewComboBoxCell)dgv.Rows[e.RowIndex].Cells[this.idxRole];
Int32 colIndex = e.ColumnIndex;
try
{
if (colIndex == this.idxIndent)
{
int number;
string cellValue = indentCell.Value.ToString();
bool isNumeric = int.TryParse(cellValue, out number);
if (!isNumeric)
{
cellValue = cellValue.Substring(0, cellValue.Length - 1);
indentCell.Value = cellValue;
}
}
// Column resizing code goes last
this.RefreshDataGridViewColumnWidths();
this.dgvIsDirty = true;
}
catch (Exception ex)
{
throw new Exception("Failed to refresh DataGridView on cell change.", ex);
}
}
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
DataGridView dgv = (DataGridView)sender;
try
{
if (dgv.IsCurrentCellDirty)
{
// This fires the cell value changed handler below
dgv.CommitEdit(DataGridViewDataErrorContexts.Commit);
this.RefreshDataGridViewColumnWidths();
}
}
catch (Exception ex)
{
throw new Exception("Failed to commit edit of DataGridView cell.", ex);
}
}
This is the code I am using to update my DataGridView contorl:
// Load the data from the database into the DataGridView
this.dbif.GetProcedure(this.procList.ElementAt(selectedIndex).PrimaryKey, ref this.dgvDataTable);
DataRow[] rows = this.dgvDataTable.Select();
//Object dgvDataSource = dgv.DataSource;
//dgv.DataSource = null;
foreach (DataRow dataRow in rows)
{
DataGridViewRow dgvRow = new DataGridViewRow();
dgvRow.CreateCells(dgv);
dgvRow.Cells[idxSection].Value = dataRow.Field<string>(0);
dgvRow.Cells[idxIndent].Value = dataRow.Field<byte>(1);
dgvRow.Cells[idxContent].Value = dataRow.Field<string>(3);
dgvRow.Cells[idxSummary].Value = dataRow.Field<UInt32>(4) != 0;
dgvRow.Cells[idxRole].Value = dataRow.Field<string>(5);
dgvRow.Cells[idxAuthor].Value = dataRow.Field<string>(6) + dataRow.Field<string>(7);
dgvRow.Cells[idxLastUpdate].Value = dataRow.Field<DateTime>(8).ToString();
dgv.Rows.Add(dgvRow);
}
//dgv.DataSource = dgvDataSource;
This is how my enumerations are defined:
public enum SectionType
{
ESJP_SECTION_HEADER = 1, // start with 1 for database compatibility
ESJP_SECTION_FOOTER,
ESJP_SECTION_BODY
}
public enum RoleType
{
ESJP_ROLE_NONE = 1, // start with 1 for database compatibility
ESJP_ROLE_TEST_ENG,
ESJP_ROLE_FEATURE_LEAD,
ESJP_ROLE_TEAM_LEAD
}
There are a number of issues/improvements. There are too many unknowns about the data to fix everything, but some techniques shown here may help.
1. Manually populating the DGV
You ought not have to do that. Just setting the DataTable as the DataSource will work most of the columns.
2. Expressions
You have 2 expressions where you populate the dgv:
dgvRow.Cells[idxSummary].Value = dataRow.Field<UInt32>(4) != 0;
dgvRow.Cells[idxAuthor].Value = dataRow.Field<string>(6) + dataRow.Field<string>(7);
This leads me to believe the dgv is ReadOnly. Otherwise you will have trouble with those. The Summary for instance: if the user Unchecks the column, you can set that value to 0, but what if they check it? How will you know what value to set??
Indent as Byte seems odd too - almost like it is a boolean.
3. Combos
In a previous question, the dgv was populated from a List<Class>. With that as the `DataSource, an Enum works well because the 2 properties were of that Type. With an enum, the following works:
cbo.ValueType = typeof(RoleType);
It's less likely to work with a DataTable as in version 1, 2 or 3 of this question because there is no db/Datatable type of SectionType or RoleType. In other cases where there is a translation - show the user "ESJP_SECTION_HEADER" but store 2 in the DataTable and ultimately the DB - a small NameValue pairs list will work. A different data model means a different approach to the DGV cbo.
It now looks like those are text columns (I've asked 3 times). If so, you really just need to constrain the selection to the enum names. In the IDE, paste in the text for the Items property:
Alternatively, you can do so in code:
private string[] secList = {"ESJP_SECTION_HEADER","ESJP_SECTION_FOOTER",
"ESJP_SECTION_BODY"};
...
((DataGridViewComboBoxColumn)dgv1.Columns["PageSection"]).Items.AddRange(secList);
AutoGenerateColumns
When the DataSource for a DGV is set, by default it will automatically create a DGVcolumn for each DTColumn, and this works well for the most part. Sometimes you'll want some small tweak like hide an Id column, or change a TextColumn to a CBOColumn. Code in the ColumnAddedEvent to make these changes rather than manually laying out columns can work well.
But since there are quite a few such such changes and since you have already layed out columns in the IDE, you want to be sure to set AutoGenerateColumns to false somewhere in code. Otherwise it will add still more columns.
Setup
Things you may or may not have done in the DGV designer:
Add the columns in whatever order you wish, but be sure to assign the DataPropertyName to the name used in the SQL query. Leave it blank for Author.
Expression columns like Author means either changing the query or doing some formatting in the DGV. For this, add First and Last name columns to the DGV as well as the Author column. Make the first two invisible. The code below shows the formatting. (Make sure that the compound column (Author) appears after the parts!).
Normally, I would try to do that in SQL: SELECT (First + Last) AS Author, but if you do not want to mess with that query, you can concat in DGV events.
Be sure to add the names for the Page and Role columns to the Items collection.
Then, the rest is fairly simple:
private DataTable dtF;
...
string SQL = "SELECT PageSection, Indent, Content, SummaryId, "
+ "UserRole, AuthorFirstN, AuthorLastN, LastUpdated FROM FellPage";
using (var dbCon = new MySqlConnection(MySQLConnStr))
using (var cmd = new MySqlCommand(SQL, dbCon))
{
dbCon.Open();
dtF = new DataTable();
dtF.Load(cmd.ExecuteReader());
}
// IMPORTANT!!!
dgv1.AutoGenerateColumns = false;
dgv1.DataSource = dtF;
The formatting event:
private void dgv1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dgv1.Rows[e.RowIndex].IsNewRow)
return;
if (e.ColumnIndex == 7) // ie "Author"
{
e.Value = dgv1.Rows[e.RowIndex].Cells[6].Value.ToString() + ", " +
dgv1.Rows[e.RowIndex].Cells[5].Value.ToString();
e.FormattingApplied = true;
}
}
Result:
It is very important to turn off AutoGenerateColumns. By default, the dgv will add columns for everything in the source. Since you added them, set that to false in the code (there is no IDE property for it).
By virtue of Summary and Indent being defined as check columns, it translates non zero as true. I have no idea how you will edit any SummaryId value. That should probably be a text column so they can enter a value, if that is allowed (that col could be read only too?).
My query and such arent as complex as yours, and surely there are some details I/we are unaware of which have been omitted. But there is certainly a much less gyrations and code to get it working...whatever this is.
Being bound to a DataTable, when the user edits anything, the changes flow thru to the underlying DataTable (use the various Validating events to check their work). The DataTable in turn tracks the state of each row - new, changed, deleted - so later you can:
var changes = dtF.GetChanges();
This will return all the rows which have been changed since the last AcceptChanges().
I'm writing a school program and I'm trying to move 3 input fields to a new page.
I can get the response.redirect to work on one field but not more.
When I click the button it takes me to the next page and only one field is brought over. Not the 3 that I'm trying to get there.
Can anyone steer my right? Thanks in advance...
Page one:
protected void btnEnterSelection_Click(object sender, EventArgs e)
{
lblBookEntered.Visible = true;
lblBookType.Visible = true;
lblPurchaseType.Visible = true;
lblBookEnteredText.Visible = true;
lblBookTypeText.Visible = true;
lblPurchaseTypeText.Visible = true;
lblBookEntered.Text = "The book you entered is: ";
lblBookEnteredText.Text = txtBoxBookTitle.Text;
lblBookType.Text = "The book type is: ";
lblBookTypeText.Text = drpDownType.Text;
lblPurchaseType.Text = "The purchase type is: ";
lblPurchaseTypeText.Text = drpDownPurchase.Text;
}
protected void btnPurchase_Click(object sender, EventArgs e)
{
Response.Redirect("turtleDoxPurchase.aspx?bookName=" + txtBoxBookTitle.Text);
Response.Redirect("turtleDoxPurchase.aspx?bookType=" + drpDownType.Text);
Response.Redirect("turtleDoxPurchase.aspx?purchaseType=" + drpDownPurchase.Text);
}
Page two:
protected void Page_Load(object sender, EventArgs e)
{
lblBookEntered.Visible = true;
lblBookType.Visible = true;
lblPurchaseType.Visible = true;
lblBookEnteredText.Visible = true;
lblBookTypeText.Visible = true;
lblPurchaseTypeText.Visible = true;
lblBookEntered.Text = "The book you entered is: ";
lblBookEnteredText.Text = Request.QueryString["bookName"];
lblBookType.Text = "The book type is: ";
lblBookTypeText.Text = Request.QueryString["bookType"];
lblPurchaseType.Text = "The purchase type is: ";
lblPurchaseTypeText.Text = Request.QueryString["purchaseType"];
lblCreditCard.Visible = true;
txtBoxCreditCard.Visible = true;
lblCreditCardChoice.Visible = true;
rdoListCreditCard.Visible = true;
btnSubmitPayment.Visible = true;
}
If I understand the problem correctly, you are trying to send three values from Page One to Page Two. In that case, you could build a Query string using the values from txtBoxBookTitle, drpDownType and DrpDownPurchase. The string should be in the follwing format:
string queryString = "?bookName={txtBoxBookTitle}&bookType={drpDownType.Value}&purchaseType={DrpDownPurchase.Value}"
Then you could append the above string to your
Response.Redirect("turtleDoxPurchase.aspx" + queryString);
Hope that helps!
I have a listview and created a textbox to search itmes in that list!
everything is ok about searching!
but problem is I want my search box to be like this:
at first Searchbox.Text="Search ..." and if user started typing in that searchbox change to that keyword! else(if) searchbox got empty Searchbox.Text change to "Search ..." again!
maybe it's a little complicated! but i tried 1-2 hours on it! and couldn't make it!
I have used Timers,checkboxchange event,booleans,...! but couldn't make it! :(
Please Help!
*my Searchbox name here is textbox1.
Some Codes I tested:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string str = textBox1.Text;
/*
if (!keywordentered_bool)
{
textBox1.Text = "";
}
*/
if (str != "")
{
//Doing Search operations!
search_bool = true;
}
else
{//Doing Search operations!
search_bool = true;
// keywordentered_checkbox.Checked = true;
Searchtextbox_Timer.Interval = 100;
Searchtextbox_Timer.Enabled = true;
Searchtextbox_Timer.Tick += Searchtextbox_Timer_Tick;
//textBox2.Visible = false;
}
}
else
{
if (search_bool)
{
listView1.Items.Clear();
label1.Visible = false;
listView1.Items.AddRange(Originalplaylist_list.ToArray());
if (!search_bool)
{
listView1.Items[MusicLogindex_list[MusicLogindex_list.Count - 1]].ForeColor = Color.Cyan;
}
else if (search_bool)
{//Doing Search operations
search_bool = false;
Searchtextbox_Timer.Interval = 100;
Searchtextbox_Timer.Enabled = true;
Searchtextbox_Timer.Tick += Searchtextbox_Timer_Tick;
//textBox2.Visible = true;
// keywordentered_checkbox.Checked = false;
}
}
void Searchtextbox_Timer_Tick(object sender, EventArgs e)
{
if (!search_bool)
{
textBox2.Visible = true;
textBox2.Location = textBox1.Location;
//textBox1.Text = "Search ...";
//textBox1.ForeColor = Color.Gray;
//textBox1.Font = new Font(textBox1.Font, FontStyle.Italic);
}
else
{
textBox2.Visible = false;
// textBox1.Text = "";
// textBox1.ForeColor = Color.Black;
// textBox1.Font = new Font(textBox1.Font, FontStyle.Regular);
}
Searchtextbox_Timer.Enabled = false;
//throw new NotImplementedException();
}
This is just psuedocode but the concept is there and you need to implement the text change event for searching , you can do additional changes in event handler.
Textbox myTxtbx = new Textbox();
myTxtbx.Text = "Enter text here...";
myTxtbx.OnFocus += OnFocus.EventHandle(RemoveText);
myTxtbx.LoseFocus += LoseFocus.EventHandle(AddText);
public RemoveText(object sender, EventArgs e)
{
myTxtbx.Text = "";
}
public AddText(object sender, EventArgs e)
{
if(string.IsNullorEmpty(myTxtbx.Text))
myTxtbx.Text = "Enter text here...";
}
This is an example shows for a dynamic textbox control, you can add these events to your control and use the same code for make it work.
Or you can use this plugin
Visual Studio gallery plugin
Another plugin you can use for this purpose
Textbox with placeholder
Hope this helps.
thanks to #Frebin Francis my problem solved!
I downloaded the source code from this link TextBox With Placeholder
and added it to my project! then add it to my form and yeah! :)
I want to create a checkbox, If that is checked then it should display the dropdown. If not checked then it should hide the dropdown. This is how my code looks in Form.Designer.cs file.
this.comboBox2.FormattingEnabled = true;
this.comboBox2.Items.AddRange(new object[] {
"Database 1",
"Database 2",
"Database 3"});
this.comboBox2.Location = new System.Drawing.Point(165, 436);
this.comboBox2.Name = "comboBox2";
this.comboBox2.Size = new System.Drawing.Size(150, 21);
this.comboBox2.TabIndex = 13;
this.comboBox2.Text = "Database";
and My checkbox code in other file is
if (checkBox1.CheckState == CheckState.Checked)
{
}
Use Visible
this.comboBox2.Visible = false;
Which would hide comboBox2.
if (checkbox1.CheckState == CheckState.Checked)
{
this.combobox2.Visible = True;
}
else (checkbox1.CheckState == CheckState.Unchecked)
{
this.combobox2.Visible = False;
}
Your going to want something like this
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
comboBox2.Visible = true;
if (checkBox1.Checked == false)
comboBox2.Visible = false;
And you will want to set the comboBox2 to visible = false in the properties tab, that should hopefully work.
Or just in one line:
comboBox2.Visible = (checkbox1.CheckState == CheckState.Checked)
If someone experiences the following:
The head of the dropwdownlist is hidden, after setting it to yourCombo.visible = false; but the list itself is still visible, then you can add the following:
yourComboBox.DroppedDown = false;
I have a form for clients to fill out, so I decided to make it an digital form. I have three pages subscriber_details, Package_Selection and Bank_Details. When the user has filled in all fields in the first and clicks next the page progresses onto the next till all three has been filled, when all three is filled they direct to a final page where all their details are presented to them for one last time, so that they can make sure its correct... on my subscriber_details.aspx I have the following code to store their details into sessions
protected void btnNext_Click(object sender, EventArgs e)
{
Session["FullName"] = txtFullName.Text;
if (txtCompanyName.Text == String.Empty)
Session["CompanyName"] = "N/A";
else
Session["CompanyName"] = txtCompanyName.Text;
if (txtVAT.Text == String.Empty)
Session["VAT"] = "N/A";
else
Session["VAT"] = txtVAT.Text;
Session["ContactNumber"] = txtContactNumber.Text;
if (txtFax.Text == String.Empty)
Session["Fax"] = "N/A";
else
Session["Fax"] = txtFax.Text;
if (txtDistrict.Text == String.Empty)
Session["District"] = "N/A";
else
Session["District"] = txtDistrict.Text;
Session["City"] = txtCity.Text;
Session["Street"] = txtStreet.Text;
Session["Code"] = txtPostal.Text;
if (txtTrading.Text == String.Empty)
Session["Trading"] = "N/A";
else
Session["Trading"] = txtTrading.Text;
Session["ID"] = txtID.Text;
Session["ContactPerson"] = txtContactPerson.Text;
if (txtEmail.Text == String.Empty)
Session["Email"] = "N/A";
else
Session["Email"] = txtEmail.Text;
}
then on my final.aspx I have the following code to use the sessions and replace the text in labels
protected void Page_Load(object sender, EventArgs e)
{
lblFullName.Text = Session["FullName"].ToString();
lblCompanyName.Text = Session["CompanyName"].ToString();
lblVat.Text = Session["VAT"].ToString();
lblContactNumber.Text = Session["ContactNumber"].ToString();
lblFax.Text = Session["Fax"].ToString();
lblDistrict.Text = Session["District"].ToString();
lblStreet.Text = Session["Street"].ToString();
lblCity.Text = Session["City"].ToString();
lblCode.Text = Session["Code"].ToString();
lblTrading.Text = Session["Trading"].ToString();
lblID.Text = Session["ID"].ToString();
lblContactPerson.Text = Session["ContactPerson"].ToString();
lblMail.Text = Session["Email"].ToString();
}
for some reason I get an "Object reference error", is it because my final.aspx page isn't my next page, because I have to pass through my package.aspx and bank_details.aspx first?
I have required field validators on the sessions that doesn't have an if statement, so the text wont be empty
You are not setting all of the Session variables. For example, you have not set Session["Email"] so the call to lblMail.Text = Session["Email"].ToString(); will throw the exception.
You should populate all Session variables you want to use and also check they are not null before doing .ToString(). This should catch it more gracefully.