CustomDataGridView Produces Duplicate Columns in Runtime - c#

My question is exactly the same as this Pls. don't down vote as the thread did not have answers.
Problem in Brief:
I have an CustomGridView, a type of DataGridView. The below code is attached to it. When I drop the datagridview in design time I can see the columns are all in proper but except for the name of the datagridviewcolumn names are different and is not what I gave.
In runtime the Columns are duplicated. Could not figure out why.
Property Page looks like this
Code:
public class CustomAccountDataGridView : DataGridView
{
private bool _paddingOn = true;
public bool PaddingOn
{
get { return _paddingOn; }
set { _paddingOn = value; }
}
public CustomAccountDataGridView()
{
this.AutoGenerateColumns = false;
this.Columns.Clear();
DataGridViewTextBoxColumn columnAccountID = new DataGridViewTextBoxColumn();
columnAccountID.DataPropertyName = "ACCOUNTID";
columnAccountID.Name = "colACCOUNTID";
columnAccountID.HeaderText = "A/c";
columnAccountID.Width = 110;
columnAccountID.Visible = false;
this.Columns.Add(columnAccountID);
DataGridViewTextBoxColumn columnClientAccountID = new DataGridViewTextBoxColumn();
columnClientAccountID.DataPropertyName = "CLIENTACCOUNTID";
columnClientAccountID.Name = "colCLIENTACCOUNTID";
columnClientAccountID.HeaderText = "Client A/c";
columnClientAccountID.Width = 110;
this.Columns.Add(columnClientAccountID);
DataGridViewTextBoxColumn columnParticipantID = new DataGridViewTextBoxColumn();
columnParticipantID.DataPropertyName = "PARTICIPANTID";
columnParticipantID.Name = "colPARTICIPANTID";
columnParticipantID.HeaderText = "Participant";
columnParticipantID.Width = 60;
this.Columns.Add(columnParticipantID);
DataGridViewTextBoxColumn columnAccountName = new DataGridViewTextBoxColumn();
columnAccountName.Name = "colACCOUNTNAME";
columnAccountName.HeaderText = "A/c Name";
columnAccountName.Width = 200;
columnAccountName.ReadOnly = true;
this.Columns.Add(columnAccountName);
DataGridViewTextBoxColumn columnXsactValue = new DataGridViewTextBoxColumn();
columnXsactValue.DataPropertyName = "XSACTVALUE";
columnXsactValue.Name = "colXSACTVALUE";
columnXsactValue.Width = 110;
columnXsactValue.HeaderText = "Value";
columnXsactValue.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
columnXsactValue.DefaultCellStyle.Format = "N2";
this.Columns.Add(columnXsactValue);
}
protected override void OnDataBindingComplete(DataGridViewBindingCompleteEventArgs e)
{
string sClientID = string.Empty;
foreach (DataGridViewRow dvr in (this.Rows))
{
for (int i = 0; i < dvr.Cells.Count; i++)
{
if (this.Columns[i].DataPropertyName == "ACCOUNTID")
{
if (dvr.Cells["colACCOUNTID"].Value != null)
{
sClientID = dvr.Cells["colACCOUNTID"].Value.ToString();
dvr.Cells["colACCOUNTNAME"].Value = sClientID; //utility.ClientExtention.getAccountName(sClientID);
break;
}
}
}
}
base.OnDataBindingComplete(e);
}
protected override void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control.GetType() == typeof(DataGridViewTextBoxEditingControl))
{
(e.Control as TextBox).CharacterCasing = CharacterCasing.Upper;
}
base.OnEditingControlShowing(e);
}
protected override void OnCellValueChanged(DataGridViewCellEventArgs e)
{
string sClientAccountID = string.Empty;
string sParticipantID = "JKB";
if (e.RowIndex >= 0)
{
if (this.Columns[e.ColumnIndex].DataPropertyName == "CLIENTACCOUNTID")
{
if (this[e.ColumnIndex, e.RowIndex].Value != null)
{
if (this[e.ColumnIndex, e.RowIndex].Value.ToString().Length != 0)
{
if (this.PaddingOn)
{
sClientAccountID = this[e.ColumnIndex, e.RowIndex].Value.ToString().ToUpper().PadLeft(13, '0');
}
else
{
sClientAccountID = this[e.ColumnIndex, e.RowIndex].Value.ToString().ToUpper();
}
this[e.ColumnIndex, e.RowIndex].Value = sClientAccountID;
}
}
}
if (this.Columns[e.ColumnIndex].DataPropertyName == "PARTICIPANTID")
{
if (this[e.ColumnIndex, e.RowIndex].Value != null)
{
if (this[e.ColumnIndex, e.RowIndex].Value.ToString().Length != 0)
{
sParticipantID = this[e.ColumnIndex, e.RowIndex].Value.ToString().ToUpper();
}
this[e.ColumnIndex, e.RowIndex].Value = sParticipantID;
}
}
if (sClientAccountID != string.Empty & sParticipantID != string.Empty)
{
this["ACCOUNTNAME", e.RowIndex].Value = (string.Format("{0}-{1}", sParticipantID, sClientAccountID));
}
}
base.OnCellValueChanged(e);
}
}
}

I found something that seems to work here:
protected override void InitLayout()
{
base.InitLayout();
SetColumns();
}
SetColumns is the subroutine to add the columns I want.

In case it can be helpful, I have just encountered this problem, on VS 2015 Express, with a standard DataGridView. The problem appeared as soon as I renamed my custom columns. Reverting to default names fixed the problem, as much as flushing the custom columns and keeping the duplicates. I can reproduce and fix the problem anytime, it seems consistent. Note that when both original and duplicate columns are in, there is no trace of the duplicates in the designer code(Designer.cs), don't ask me why...

Related

C# did not accepting checked property

try
{
DataRowView drv = attDataGrid.SelectedItem as DataRowView;
att_id = Convert.ToInt32(drv.Row[0].ToString());
attComboBox.SelectedItem = drv.Row[1].ToString();
rdata = drv.Row[2].ToString(); ;
attDetail.Text = drv.Row[4].ToString();
DateTime sdt = dc.changeDateG(drv.Row[3].ToString());
if(rdata.Equals("حاضر"))
{
attPre.Checked = true;
}
else {
attUp.Checked = true;
}
try
{
attDate.SelectedDate = sdt;
}
catch (FormatException)
{
MessageBox.Show(sdt.ToString());
}
}
catch(NullReferenceException)
{
}
I am trying to set my attPre radio button checked but visual studio takes it as error any idea how to deal with this error???
Probably because you doing comparision not assignment
Use this:
attPre.Checked = true;
Instead of
attPre.Checked == true;
I have found out how to deal with it
RadioButton pr = attPre as RadioButton;
pr.IsChecked = true;

Stop SelectedValueChanged event

I just want to ask how to stop the selected value changed event in my code. I have both SelectedValueChanged event and SelectedIndexChanged event. I am using SelectedIndexChanged event because to find any duplication on my gridview for you to understand, here is my code.
SelectedValueChanged code:
private void cmbField_SelectedValueChanged(object sender, EventArgs e)
{
DataGridViewRow GridRowLoc = this.dgvFilter.CurrentRow;
AddGrid(iRowIdx);
int iRowCount = this.dgvFilter.RowCount - 1;
if (this.cmbField.Text != "System.Data.DataRowView")
{
this.dgvFilter.Rows[iRowIdx].Cells["ColumnFieldName"].Value = this.cmbField.Text;
this.dgvFilter.Rows[iRowIdx].Cells["FieldName"].Value = this.cmbField.SelectedValue;
if (iRowCount <= iRowIdx)
{
DataRow drow = dttable.NewRow();
drow["ColumnNames"] = this.cmbField.Text;
drow["FieldName"] = this.cmbField.SelectedValue;
drow["Alias"] = string.Empty;
drow["DataType"] = string.Empty;
drow["Outputs"] = false;
drow["SortType"] = string.Empty;
drow["SortOrder"] = string.Empty;
drow["GroupBy"] = string.Empty;
drow["Filter"] = string.Empty;
drow["Or1"] = string.Empty;
drow["Or2"] = string.Empty;
drow["Or3"] = string.Empty;
drow["Or4"] = string.Empty;
drow["Or5"] = string.Empty;
drow["Or6"] = string.Empty;
drow["Or7"] = string.Empty;
drow["Or8"] = string.Empty;
drow["Or9"] = string.Empty;
drow["Or10"] = string.Empty;
dttable.Rows.Add(drow);
}
else
{
int irow = 0;
foreach (DataRow dr in dttable.Rows)
{
if (irow == iRowIdx)
{
dr["ColumnNames"] = this.cmbField.Text;
dr["FieldName"] = this.cmbField.SelectedValue;
}
irow++;
}
}
CheckAlias(iRowIdx, this.cmbField.Text, dgvFilter);
checkcellvalue(this.cmbField.Text, iRowIdx);
CheckSorting();
if (bGroupBySelected == true)
{
this.dgvFilter.Rows[iRowIdx].Cells["GroupBy"].Value = "Group By";
}
this.dgvFilter.DataSource = dttable;
dsFilter.AcceptChanges();
this.cmbField.Visible = false;
}
//checkcellvalue(this.cmbField.Text, iRowIdx);
//MessageBox.Show(arr_Filter[0]);
CheckoutputEnable();
}
Then here is my SelectedIndexChanged code:
private void cmbField_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (dgvFilter.Rows.Count > 1)
{
int count = this.dgvFilter.Rows.Count;
DataRowView oDataRowView = cmbField.SelectedItem as DataRowView;
string sValue = string.Empty;
if (oDataRowView != null)
{
sValue = oDataRowView.Row["FieldDescription"] as string;
}
for (int j = 0; j < count; j++)
{
sValue = this.cmbField.Text;
if ((j + 2) != dgvFilter.Rows.Count)
{
if ((sValue == this.dgvFilter.Rows[j].Cells["ColumnFieldName"].Value.ToString()))
{
if (this.dgvFilter.Rows.Count > 2)
{
MessageBox.Show("Field already in the list");
DataGridViewRow GridRowLoc2 = this.dgvFilter.CurrentRow;
this.dgvFilter.Rows.Remove(GridRowLoc2);
break;
}
}
}
}
}
}
catch (Exception ex)
{
}
}
My code upon loading the form is this in case you guys need.
private void FormAdhocReportViewer_Load(object sender, EventArgs e)
{
try
{
//string sample = "";
sXMLResult = SQLScript;
AddGrid(0);
adhoc.RowID = CurrentUserNameRowID;
adhoc.FieldGroup = toolStripReportGroup.Text;
XMLDOC = adhoc.get_sp_Get_Field_Settings();
if (RowID == "0")
{
// XMLDOC = adhoc.get_sp_Get_Field_Settings();
LoadDataSet(XMLFILTER);
}
else
{
// XMLDOC = sXMLFieldSettings;
XMLFieldQuery = XMLFieldQuery.Replace("#", "<").Replace("+", ">").Replace("*", "/");
LoadDataSet(XMLFieldQuery);
}
LoadComboField();
}
catch { }
}
LoadComboField is for the items in the combobox, the code is this
private void LoadComboField()
{
ReadXMLData(XMLDOC, dsCombo);
dt = dsCombo.Tables[0];
DataView dv1 = new DataView(dsCombo.Tables[0]);
this.cmbField.Items.Clear();
this.cmbField.DataSource = dv1;
this.cmbField.DisplayMember = "FieldDescription";
this.cmbField.ValueMember = "FieldName";
}
Everytime the code
DataGridViewRow GridRowLoc2 = this.dgvFilter.CurrentRow;
this.dgvFilter.Rows.Remove(GridRowLoc2);
executes the event SelectedValueChanged executes to.. I just want to stop the SelectedValueChangedEvent it's so hard to explain because my code is too complicated.
What about simply removing the event handler?
Just do:
if (<whatever>)
{
this.cmbField.SelectedValueChanged -= cmbField_SelectedValueChanged;
}

Assigning checkbox a value from gridview

I am selecting a row from Gridview, working good except for checkbox, like I am assigning value of checkbox retreived from gridview to checkbox that is placed on web form but it isn't represented by checkbox on form, it shows empty checkbox in every case
if (gridviewDesignations.SelectedRow.Cells[5].Text == " ")
{
chkIsHead.Text = gridviewDesignations.SelectedRow.Cells[5].Text;
}
in short, checkbox is not picking value from gridview
Update:
tried this too:
CheckBox chkIsHead = (CheckBox) gridviewDesignations.SelectedRow.Cells[5].Controls[0];
if (chkIsHead.Checked == false)
{
chkIsHead.Checked = false;
}
else
{
chkIsHead.Checked = true;
}
Update:
my full code:
public partial class frmDesignations : System.Web.UI.Page
{
AccessibleVariables accessVariables = new AccessibleVariables(); //Used to access global variables
public void Clear(params TextBox[] txtBoxes)
{
foreach (TextBox txtbx in txtBoxes)
{
txtbx.Text = "";
}
}
public void fillddlDepartments()
{
ManageDepartmentsBizz mngDepBizz = new ManageDepartmentsBizz();
DataSet ds = (DataSet)mngDepBizz.SelectDepartments();
if (ds.Tables[0].Rows.Count != 0)
{
ddlDepartments.DataValueField = "DepID";
ddlDepartments.DataTextField = "DepName";
ddlDepartments.DataSource = ds.Tables[0];
// ddlDepartments.SelectedIndex = -1;
ddlDepartments.DataBind();
ddlDepartments.Items.Insert(0, "--Select--");
}
//else
// ddlDepartments.SelectedIndex = -1;
}
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count <= 0)
{
Response.Redirect("login.aspx");
}
lblMsgPopUp.Visible = false;
if (!IsPostBack)
{
fillddlDepartments();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
int DepartmentID = Convert.ToInt32(ddlDepartments.SelectedValue);
bool IsHead = Convert.ToBoolean(chkIsHead.Checked);
DesignationsBizz DesigBizz = new DesignationsBizz(-1, txtTitle.Text, DepartmentID, txtContactNo.Text, IsHead);
//-1 is bogus,used to fill parameters criteria i.e no of params
ManageDesignationsBizz mngDesigBizz = new ManageDesignationsBizz();
bool Result = mngDesigBizz.Insert(DesigBizz);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Saved";
HiddenFieldShowMessage.Value = "True";
Clear(txtTitle, txtSelectedID, txtContactNo);
}
else
{
HiddenFieldSetMessage.Value = "RecordAlreadyExists";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotSaved";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnSearchPopup_Click(object sender, EventArgs e)
{
string DesignationTitle = txtDesignationPopUp.Text;
ManageDesignationsBizz mngDepsBizz = new ManageDesignationsBizz();
DataSet ds = (DataSet)mngDepsBizz.Select(DesignationTitle);
if (ds.Tables[0].Rows.Count != 0)
{
lblMsgPopUp.Visible = false;
gridviewDesignations.DataSource = ds.Tables[0];
gridviewDesignations.DataBind();
gridviewDesignations.Visible = true;
}
else
{
lblMsgPopUp.Visible = true;
gridviewDesignations.Visible = false;
}
}
protected void gridviewDesignations_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
string DesignationTitle = txtDesignationPopUp.Text;
ManageDesignationsBizz mngDepBizz = new ManageDesignationsBizz();
DataSet ds = (DataSet)mngDepBizz.Select(DesignationTitle);
if (ds.Tables[0].Rows.Count != 0)
{
gridviewDesignations.PageIndex = e.NewPageIndex;
gridviewDesignations.DataSource = ds.Tables[0];
gridviewDesignations.DataBind();
gridviewDesignations.Visible = true;
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
if (gridviewDesignations.SelectedRow != null)
{
if (gridviewDesignations.SelectedRow.Cells[1].Text == " ")
{
txtSelectedID.Text = string.Empty;
}
else
{
txtSelectedID.Text = gridviewDesignations.SelectedRow.Cells[1].Text;
}
if (gridviewDesignations.SelectedRow.Cells[2].Text == " ")
{
txtTitle.Text = string.Empty;
}
else
{
txtTitle.Text = gridviewDesignations.SelectedRow.Cells[2].Text;
}
if (gridviewDesignations.SelectedRow.Cells[3].Text == " ")
{
ddlDepartments.SelectedValue = string.Empty;
}
else
{
ddlDepartments.SelectedValue = gridviewDesignations.SelectedRow.Cells[3].Text;
accessVariables.DepID = Convert.ToInt32(gridviewDesignations.SelectedRow.Cells[3].Text);
ViewState["depID"] = accessVariables.DepID;
}
if (gridviewDesignations.SelectedRow.Cells[4].Text == " ")
{
txtContactNo.Text = string.Empty;
}
else
{
txtContactNo.Text = gridviewDesignations.SelectedRow.Cells[4].Text;
}
CheckBox chkIsHead = (CheckBox) gridviewDesignations.SelectedRow.Cells[5].Controls[0];
if (chkIsHead.Checked == false)
{
chkIsHead.Checked = false;
}
else
{
chkIsHead.Checked = true;
}
gridviewDesignations.DataBind();
gridviewDesignations.SelectedIndex = -1;
HiddenFieldShowHideButtons.Value = "True";
}
}
protected void btnUpdatePopUp_Click(object sender, EventArgs e)
{
try
{
int id = Convert.ToInt32(txtSelectedID.Text);
int DepartmentID = Convert.ToInt32(ddlDepartments.SelectedValue);
bool IsHead = Convert.ToBoolean(chkIsHead.Checked);
DesignationsBizz DesigBizz = new DesignationsBizz(id, txtTitle.Text, DepartmentID, txtContactNo.Text, IsHead );
ManageDesignationsBizz mngDesigBizz = new ManageDesignationsBizz();
bool Result = mngDesigBizz.Update(DesigBizz);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Updated";
HiddenFieldShowMessage.Value = "True";
Clear(txtSelectedID, txtTitle, txtContactNo);
}
else
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnDeletePopUp_Click(object sender, EventArgs e)
{
try
{
int ID = Convert.ToInt32(txtSelectedID.Text.Trim());
ManageDesignationsBizz mngDepBizz = new ManageDesignationsBizz();
mngDepBizz.Delete(ID);
Clear(txtTitle, txtSelectedID, txtContactNo);
HiddenFieldSetMessage.Value = "Deleted";
HiddenFieldShowMessage.Value = "True";
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotDeleted";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnClosePopup_Click(object sender, EventArgs e)
{
Clear(txtTitle, txtSelectedID, txtContactNo);
}
protected void ddlDepartments_SelectedIndexChanged(object sender, EventArgs e)
{
if (txtSelectedID.Text != "")
{
accessVariables.DepID = Convert.ToInt32(ddlDepartments.SelectedValue);
ViewState["depID"] = accessVariables.DepID;
}
else
{
accessVariables.DepID = Convert.ToInt32(ddlDepartments.SelectedValue);
ViewState["depID"] = accessVariables.DepID;
}
}
protected void chkIsHead_CheckedChanged(object sender, EventArgs e)
{
if (txtSelectedID.Text != "")
{
int DepID = Convert.ToInt32(ViewState["depID"]);
ManageDesignationsBizz mngDesig = new ManageDesignationsBizz();
bool isHead = mngDesig.SelectIsHeadExistsByDepID(DepID);
if (isHead == true)
{
HiddenFieldSetMessage.Value = "HeadExists";
HiddenFieldShowMessage.Value = "True";
chkIsHead.Checked = false;
}
}
else
{
int DepID = Convert.ToInt32(ViewState["depID"]);
ManageDesignationsBizz mngDesig = new ManageDesignationsBizz();
bool isHead = mngDesig.SelectIsHeadExistsByDepID(DepID);
if (isHead == true)
{
HiddenFieldSetMessage.Value = "HeadExists";
HiddenFieldShowMessage.Value = "True";
chkIsHead.Checked = false;
}
}
}
}
I believe the following is what you need to do:
Then select EditProgrammatically.
I'm not sure if yoou'll need to manually put data into the grid though but that won't be too hard. Examples can be seen here : http://msdn.microsoft.com/en-us/library/system.data.datatable(v=vs.110).aspx
PS : You can set the DataSource in the grid view to the DataTable.

Error: "Input string was not in a correct format" on false statement

My code is working fine if the statement (numtickets > tickav) is true (if tickets available is greater than tickets ordered) But if other wise, it throws in this error "FormatException was unhandled by user code, Input string was not in a correct format" on int numTick = Convert.ToInt32(txtNumberOfTickets.Text);
I do know that somehow I can use tryparse, i need help putting it in the code.
Any help would be appreciated, thank you
namespace TicketsApp
{
public partial class TicketOrder : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["description"] != null && Session["EventID"] != null && Session["numtickets"] != null && Session["ticketcost"] != null
&& Session["State"] != null && Session["Section"] != null && Session["Row"] != null && Session["date"] != null)
{
if (!IsPostBack)
{
try
{
txtEventDescription.Text = Session["description"].ToString();
txtEventID.Text = Session["EventID"].ToString();
txtTicketsAvailable.Text = Session["numtickets"].ToString();
txtTicketCost.Text = Session["ticketcost"].ToString();
txtState.Text = Session["State"].ToString();
txtSectionNumber.Text = Session["Section"].ToString();
txtRowNumber.Text = Session["Row"].ToString();
txtNumberOfTickets.Focus();
lblOutput.Visible = false;
}
catch
{
lblError.Text = "Please Search for Tickets First!";
lblError.Visible = true;
btnOrderTickets.Visible = false;
Response.Redirect("TicketSearch.aspx");
return;
}
}
}
}
protected void btnOrderTickets_Click(object sender, EventArgs e)
{
TicketsDataAccessDataContext NewOrder = new TicketsDataAccessDataContext();
int numTick = Convert.ToInt32(txtNumberOfTickets.Text);
string s = txtTotalCost.Text.Substring(1);
int totc = Convert.ToInt32(s);
int id = Convert.ToInt32(txtEventID.Text);
DateTime dt = Convert.ToDateTime(Session["date"]);
int returnedValue = NewOrder.PlaceOrderFull(id, txtEventDescription.Text, dt, Session["State"].ToString(), Session["section"].ToString(), Session["Row"].ToString(), numTick, totc, "vfateev");
if (returnedValue != 0)
{
lblOutput.Text = "Error has occured. Please try again";
lblOutput.Visible = true;
btnOrderTickets.Visible = false;
}
else
{
lblOutput.Visible = true;
lblOutput.Text = "Thank you";
btnOrderTickets.Visible = false;
}
}
protected void txtNumberOfTickets_TextChanged1(object sender, EventArgs e)
{
int cos = Convert.ToInt32(txtTicketCost.Text);
int numtickets = Convert.ToInt32(txtNumberOfTickets.Text);
int tickav = Convert.ToInt32(txtTicketsAvailable.Text);
if (numtickets > tickav)
{
lblError.Text = "Please Enter a valid ticket quantity";
lblError.Visible = true;
lblOutput.Text = "";
txtNumberOfTickets.Text = "";
}
else
{
int cost = cos * numtickets + 5;
txtTotalCost.Text = "$" + cost.ToString();
lblOutput.Visible = false;
lblFee.Text = "There is a $5 shipping fee";
lblFee.Visible = true;
lblError.Text = "";}
}
}
}
You can use int.TryParse which returns a boolean and does not throw an exception.
int numTick = 0;
bool result = int.TryParse(txtNumberOfTickets.Text, out numTick );
You can also do some client side validation to ensure that the field is filled in and contains a number.
Here is one of your methods rewritten using Int32.TryParse. I assumed you're doing txtTotalCost.Substring(1) to trim off the currency symbol. There are probably safe ways to do this, I'm just going to trim "$" for this example.
protected void btnOrderTickets_Click(object sender, EventArgs e)
{
int numberOfTickets, ticketCost, eventId;
if(Int32.TryParse(txtNumberOfTickets.Text, out numberOfTickets) &&
Int32.TryParse(txtTotalCost.Text.TrimStart('$'), out ticketCost) &&
Int32.TryParse(txtEventID.Text, out eventId))
{
DateTime dt = Convert.ToDateTime(Session["date"]);
TicketsDataAccessDataContext NewOrder = new TicketsDataAccessDataContext();
int returnedValue = NewOrder.PlaceOrderFull(eventId, txtEventDescription.Text, dt, Session["State"].ToString(), Session["section"].ToString(), Session["Row"].ToString(), numberOfTickets, ticketCost, "vfateev");
if (returnedValue != 0)
{
lblOutput.Text = "Error has occured. Please try again";
lblOutput.Visible = true;
btnOrderTickets.Visible = false;
}
else
{
lblOutput.Visible = true;
lblOutput.Text = "Thank you";
btnOrderTickets.Visible = false;
}
}
else
{
lblOutput.Visible = true;
lblOutput.Text = "Some validation error message here...";
}
}
You will need to make similar modifications to txtNumberOfTickets_TextChanged1 to ensure the user has entered valid text.
simply use something like
To use IsNumeric in C#, add a reference to Microsoft.VisualBasic.dll then
if (Information.IsNumeric(value))
{
DoSomthing();
}
else
{
DoSomethingElse();
}
UPDATE
OPEN VISUAL STUDIO ==> YOUR PROJECT
Click on solution and add reference, choose Microsoft.VisualBasic.dll confrim the new reference will be add to your references into the project.
Go at the top of your page and declare the import statemnet for Microsoft.VisualBasic.dll alias
using Microsoft.VisualBasic.dll;
then where you need to check the value of your textbox
if (Information.IsNumeric(yourtextbox.text.trim()))
{
//case true alias your value is numeric
//do what you need here like assing value to a var or any
//else
}
else
{
//put your logic here in case result is false and value
//is not numeric
}

clear each thing after doing achieving a specific task

i am working on an software in which i want to clear each thing after doing achieving a specific task, like clearing all the fields, list view etc etc and i've to write the a lot of things to be cleared off, like the code of my new button is:
private void btnNew_Click(object sender, EventArgs e)
{
txtProductCode1.ReadOnly = false;
txtInvoiceNo.ReadOnly = false;
cmbCustoemerType.Enabled = false;
cmbCustomerName.Enabled = false;
button1.Enabled = true;
txtProductCode1.Text = null;
txtWageName.Text = null;
txtWageCost.Text = null;
btnFirst.Visible = false;
btnPrevious.Visible = false;
btnNext.Visible = false;
btnLast.Visible = false;
cmbProductName.Enabled = true;
txtQty.ReadOnly = false;
txtPercant.ReadOnly = false;
txtDiscount.ReadOnly = false;
cmbCustoemerType.Enabled = true;
cmbCustomerName.Enabled = true;
button5.Enabled = true;
btnDelete.Enabled = true;
dtp1.Enabled = true;
btnSave.Text = "&Save";
cmbCustoemerType.Text = null;
cmbCustomerName.Text = null;
txtInvoiceNo.Clear();
txtDiscount.Clear();
txtGrandTotal.Clear();
txtProductName.Clear();
txtSalePrice.Clear();
txtQty.Clear();
txtTotal.Clear();
txtExtraWages.Text = null;
lvExtraWages.Items.Clear();
lvTransaction.Items.Clear();
lblCount.Text = null;
lblNetTotal.Text = null;
txtPercant.Text = null;
txtInvoiceNo.Text = invoice.ToString();
}
is there any way to get rid of writing the code again n again, like i need to enable one thing which i've disabled here on another button so i have to write reverse code of this to achieve the task and it's really annoying! is there any other way to do this?
EDIT:
tried following code:
private void btnNew_Click(object sender, EventArgs e)
{
//using setboxdefault function
SetTextBoxDefaults();
cmbCustoemerType.Text = null;
cmbCustomerName.Text = null;
cmbCustoemerType.Enabled = false;
cmbCustomerName.Enabled = false;
cmbProductName.Enabled = true;
cmbCustoemerType.Enabled = true;
cmbCustomerName.Enabled = true;
button5.Enabled = true;
btnDelete.Enabled = true;
button1.Enabled = true;
btnFirst.Visible = false;
btnPrevious.Visible = false;
btnNext.Visible = false;
btnLast.Visible = false;
btnSave.Text = "&Save";
lvExtraWages.Items.Clear();
lvTransaction.Items.Clear();
lblCount.Text = null;
lblNetTotal.Text = null;
dtp1.Enabled = true;
txtInvoiceNo.Text = invoice.ToString();
}
private void SetTextBoxDefaults()
{
var textBoxes = GetControls(this, typeof(TextBox));
foreach (var textBox in textBoxes)
{
TextBox.Clear();
}
}
public IEnumerable<Control> GetControls(Control control, Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetControls(ctrl, type)).Concat(controls).Where(c => c.GetType() == type);
}
but it's giving error on TextBox.Clear(); , error is Error 4
An object reference is required for the non-static field, method, or property 'System.Windows.Forms.TextBoxBase.Clear()'
Please let me know where i am mistaking..!!
As Tim has suggested, you can iterate though the controls and set each one accordingly..
public IEnumerable<Control> GetControls(Control control,Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetControls(ctrl,type)).Concat(controls).Where(c => c.GetType() == type);
}
private void btnNew_Click(object sender, EventArgs e)
{
SetComboBoxDefaults();
SetTextBoxDefaults();
SetButtonDefaults();
}
private void SetComboBoxDefaults()
{
var comboBoxes = GetControls(this, typeof(ComboBox));
foreach (var comboBox in comboBoxes)
{
((ComboBox)comboBox).Enabled = false;
((ComboBox)comboBox).Text = null;
}
}
private void SetTextBoxDefaults()
{
var textBoxes = GetControls(this, typeof(TextBox));
foreach (var textBox in textBoxes)
{
((TextBox)textBox).Clear();
}
}
private void SetButtonDefaults()
{
var buttons = GetControls(this, typeof(Button));
foreach (var button in buttons)
{
((Button)button).Visible = false;
if (button.Name == "btnSave") ((Button)button).Text = "&Save";
}
}
You can also have separate GetControl methods so that it returns a specific type of Control, reducing the need to cast to derived types.
update for edit:
You are using the TextBox type instead of the variable name in the foreach loop. Update it to use textBox (lowercase), not TextBox (pascal) see below:
private void SetTextBoxDefaults()
{
var textBoxes = GetControls(this, typeof(TextBox));
foreach (var textBox in textBoxes)
{
((TextBox)textBox).Clear();
}
}
Remember to stay DRY
Don't
Repeat
Yourself
Partition the reset logic into suitable, small methods that reset a logical grouping of controls. Then invoke those methods where and as needed.
What I have done in several such cases is this:
void SetTextBoxReadOnly(bool val, param TextBox[] textBoxes)
{
if(textBoxes != null && textBoxes.Length > 0)
{
foreach(TextBox textBox in textBoxes)
{
if(textBox != null)
{
textBox.ReadOnly = val;
}
}
}
}
void SetControlEnabled(bool val, param Control[] ctrls)
{
if(ctrls != null && ctrls.Length > 0)
{
foreach(Control ctrl in ctrls)
{
if(ctrl != null)
{
ctrl.Enabled = val;
}
}
}
}
// etc set of methods for similar situations.
// there methods can be invoked as
...
...
...
SetTextBoxReadOnly(true, txtProductCode1,
txtInvoiceNo,
txtQty,
txtPercant,
txtDiscount);

Categories

Resources