objects in datagridview - c#

Im adding objects to a datagridview ( only one kind) through a list
ej.
List<Material> mater = new List<Material>();
DataGridView dgvMAterial = new DataGridView();
dgvMaterial.DataSource = null;
mater.Add((Material)cmbMaterial.SelectedValue);
dgvMaterial.DataSource = mater;
But every time I click over the datagrid I get an indexoutofrangeexeption.
Can somone tell me why?
thanks
here is my whole code for the form
public partial class inicio : Form
{
private string ConnectionString = "Data Source=localhost\\sqlexpress;Initial Catalog=data.mdf;Integrated Security=SSPI;";
//private string ConnectionString = "Server=.\\SQLExpress;AttachDbFilename=|DataDirectory|\\data\\data_data.mdf.mdf; Database=data.mdf;Trusted_Connection=Yes;";
private ISessionFactory sessionFactory;
List<Material> mater = new List<Material>();
List<Salarios> salar = new List<Salarios>();
IBindingList mind = new BindingList<Salarios>();
Productos prod;
public inicio()
{
InitializeComponent();
sessionFactory = nhn.BusinessObjects.Initialize.CreateSessionFactory(ConnectionString);
dgvMaterial.DataSource = mater;
}
private void materialToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmMaterial material = new costeos.Catalogos.frmMaterial(ConnectionString);
material.ShowDialog(this);
material.Dispose();
}
private void salariosToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmSalarios salarios = new costeos.Catalogos.frmSalarios(ConnectionString);
salarios.ShowDialog(this);
salarios.Dispose();
}
private void agregarToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmAddRemuneraciones rem = new costeos.Catalogos.frmAddRemuneraciones(ConnectionString);
rem.ShowDialog(this);
rem.Dispose();
}
private void agregarToolStripMenuItem1_Click(object sender, EventArgs e)
{
Catalogos.frmAddAdmin adm = new costeos.Catalogos.frmAddAdmin(ConnectionString);
adm.ShowDialog(this);
adm.Dispose();
}
private void agregarToolStripMenuItem2_Click(object sender, EventArgs e)
{
Catalogos.frmAddInsumosInd insumos = new costeos.Catalogos.frmAddInsumosInd(ConnectionString);
insumos.ShowDialog(this);
insumos.Dispose();
}
private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) || char.IsPunctuation(e.KeyChar) || char.IsControl(e.KeyChar))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
private void inicio_Load(object sender, EventArgs e)
{
LlenaCampos();
}
private void LlenaCampos()
{
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var mat = session.CreateCriteria(typeof(Material))
.List<Material>();
var sal = session.CreateCriteria(typeof(Salarios))
.List<Salarios>();
transaction.Commit();
cmbMaterial.DataSource = mat;
cmbMaterial.DisplayMember = "Nombre";
cmbSalarios.DataSource = sal;
cmbSalarios.DisplayMember = "Nombre";
cmbMIndirecta.DataSource = sal;
cmbMIndirecta.DisplayMember = "Nombre";
}
}
}
private void btnAddMaterial_Click(object sender, EventArgs e)
{
materialBindingSource.DataSource = null;
//dgvMaterial.DataSource = null;
mater.Add((Material)cmbMaterial.SelectedValue);
//dgvMaterial.DataSource = mater;
dgvMaterial.DataSource = materialBindingSource;
materialBindingSource.DataSource = mater;
materialBindingSource.ResetBindings(false);
}
private void button2_Click(object sender, EventArgs e)
{
dgvSalarios.DataSource = null;
salar.Add((Salarios)cmbSalarios.SelectedValue);
dgvSalarios.DataSource = salar;
}
private void button3_Click(object sender, EventArgs e)
{
dgvMIndirecta.DataSource = null;
mind.Add((Salarios)cmbMIndirecta.SelectedValue);
dgvMIndirecta.DataSource = mind;
}
private void button1_Click(object sender, EventArgs e)
{
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
if (prod == null)
{
prod = new Productos { CargasTurno = float.Parse(txtCargasTurno.Text), CavidadesMolde = int.Parse(txtCavidadesMolde.Text), Clave = txtClave.Text, Comentarios = txtComentarios.Text, MezclasTurno = float.Parse(txtMezclasTurno.Text), Moldes = int.Parse(txtMoldes.Text), Nombre = txtNombre.Text, Peso = float.Parse(txtPesoTotal.Text), TotalPza = int.Parse(txtPzasTotales.Text), Turnos = int.Parse(txtTurnos.Text) };
session.Save(prod);
transaction.Commit();
}
foreach (DataGridViewRow dr in dgvMaterial.Rows)
{
Material m = dr.DataBoundItem as Material;
m.Materiales
PMaterial mat = new PMaterial { Material = dr.DataBoundItem as Material, Cantidad = float.Parse(dr.Cells["Cantidad"].Value.ToString()), Fecha = DateTime.Now, Producto = prod };
session.Save(mat);
}
transaction.Commit();
session.Close();
}
}
}
}
}

That's probably not DGV problem, but with this combo box. Show us the code that fills combo box and sets its properties.
If you are casting to Material class you should probably use SelectedItem instead of SelectedValue. (unless you exactly know what you're doing)

I would guess that you have an event-handler that isn't happy. What exactly does the message say?
You might also be having problems if you are adding the same Material instance to the list multiple times; since IndexOf will only find the first occurrence. This line makes me very suspicious:
mater.Add((Material)cmbMaterial.SelectedValue);
since it could potentially (on consecutive clicks / etc) do exactly this.
Note: if you used BindingList<T> instead all you'd have to doo is Add(...) - no resetting required:
field:
BindingList<Material> mater = new BindingList<Material>();
init grid:
dgvMaterial.DataSource = mater;
add item:
mater.Add(newInstance);

If you assign data source to the DGV you should check element count - if zero then assign null. I don't know why this is the way it is, but I'm doing it in all my forms.
//I'm still analysing the rest of the code

Related

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

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

C#_Timer/Stopwatch unable to continue from time extracted from database

I have below code to start and stop timer/stopwatch and load value into database.
The stopwatch works fine, and time is able to load into database and extract from database into textbox.
the problem is after i extract the time from database and insert into text box, then i start timer, it didnt start from current time. It always start from 0.
there is no error when running the program.
Could anyone help for troubleshoot please? Thanks in advance!
public partial class TestWindow : Window
{
String SNconnectionstring = (#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SNDB.mdf;Integrated Security=True;");
DispatcherTimer dtSN = new DispatcherTimer();
Stopwatch swSN = new Stopwatch();
string currentTimeSN = string.Empty;
public TestWindow()
{
InitializeComponent();
}
private void SNCreate_Click(object sender, RoutedEventArgs e)
{
using (SqlConnection sqlConSN = new SqlConnection(SNconnectionstring))
{
sqlConSN.Open();
SqlCommand sqlCmdSN = new SqlCommand("SNadd", sqlConSN);
sqlCmdSN.CommandType = System.Data.CommandType.StoredProcedure;
sqlCmdSN.Parameters.AddWithValue("#SN", sNtxtbox.Text);
sqlCmdSN.Parameters.AddWithValue("#Time", SNTime.Text.Trim());
sqlCmdSN.ExecuteNonQuery();
}
private void Open_Click(object sender, RoutedEventArgs e)
{
using (SqlConnection sqlConSN = new
SqlConnection(SNconnectionstring))
{
sqlConSN.Open();
String sqlSelectQuerySN = ("Select * FROM tblSN WHERE SN = #SN");
SqlCommand sqlCmdSNLoad = new SqlCommand(sqlSelectQuerySN, sqlConSN);
sqlCmdSNLoad.Parameters.Add("#SN", System.Data.SqlDbType.VarChar).Value = sNtxtbox.Text;
SqlDataReader drSNReader = sqlCmdSNLoad.ExecuteReader();
if (drSNReader.Read())
{
SNTime.Text = (drSNReader["Time"].ToString());
}
else
{
SNTime.Text = "";
}
}
private void sNbtn_Click(object sender, RoutedEventArgs e)
{
TabControl.SelectedIndex = 1;
dtSN.Tick += new EventHandler(dtSN_Tick);
dtSN.Interval = new TimeSpan(0, 0, 0, 0, 1);
}
void dtSN_Tick(object sender, EventArgs e)
{
if (swSN.IsRunning)
{
TimeSpan tsSN = swVASN.Elapsed;
currentTimeSN = string.Format("{0:00}:{1:00}:{2:00}", tsSN.Hours, tsSN.Minutes, tsSN.Seconds);
txtSN.Text = currentTimeSN;
}
}
private void btnTimeStartSN_Click(object sender, RoutedEventArgs e)
{
swSN.Start();
dtSN.Start();
}
private void btnTimeStopSN_Click(object sender, RoutedEventArgs e)
{
if (swSN.IsRunning)
{
swSN.Stop();
}
}

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

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

Why multiply items in a ListView?

I created in the Loaded event of the main page, a List with some objects of my class "Regioni" and "Musei"
Then I added these items in a ListView, and SelectedItem event recovery the selected object and take it in a new page
private void Page_Loaded(object sender, RoutedEventArgs e)
{
reg.Add(
new Regioni
{
NomeRegione = "Toscana",
NomeProvincia = "Firenze"
});
reg.Add(
new Regioni
{
NomeRegione = "Toscana",
NomeProvincia = "Prato"
});
var gruppi = reg.OrderBy(x => x.NomeRegione).GroupBy(x => x.NomeRegione);
Museum.Source = gruppi;
mus.Add(
new Musei
{
NomeMuseo = "Galleria degli Uffizi",
Paese = "Firenze",
NumeroTel = "055294883",
IndirizzoEmail = "mbac-sspsae-fi#beniculturali.it",
PrezzoBiglietto = "8 € Intero, 4€ Ridotto\r\nGratuito inferiore 18 anni",
Apertura = "Da martedì a domenica,\r\nore 8,15-18,50 Chiusura: Lunedi,Capodanno,Natale,1° Maggio.",
IndirizzoWeb = "http://uffizi.firenze.it/",
Immagine="Assets/Immagini/galleria-uffizi1.jpg",
});
}
private async void ListView_ItemClick_TuttiMusei(object sender, ItemClickEventArgs e)
{
var NuovoMuseo = (Musei)e.ClickedItem;
this.Frame.Navigate(typeof(DettaglioMuseo), NuovoMuseo);
}
Why when I insert the object into the new page "DettaglioMuseo", and go back on the main page, in the ListView I find the same items twice?
This happens because the Loaded-event fires again and adds the items again.
So you should check if your Regionis already exist before adding them:
private void Page_Loaded(object sender, RoutedEventArgs e)
{
AddIfNotExists("Toscana", "Firenze");
AddIfNotExists("Toscana", "Prato");
var gruppi = ...
...
}
private void AddIfNotExists(string regione, string provincia)
{
if (!reg.Any(r => r.NomeProvincia == regione && r.NomeProvincia == provincia))
{
reg.Add(new Regioni { NomeRegione = regione, NomeProvincia = provincia });
}
}

-C# Label & Literal not displaying value

I have a profile that allows users to display, edit, save.
The save and edit works ok.
However, the display is not working properly.
I tried changing labels to literals but they don't either.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGenderDropDownList();
//this.BindTimeZonesDropDownList();
//this.BindCulturesDropDownList();
if (!string.IsNullOrEmpty(Membership.GetUser().UserName))
{
Profile = MyProfile.GetProfile(Membership.GetUser().UserName);
this.DisplayProfile();
}
}
}
protected void btnGo_Click(object sender, EventArgs e)
{
this.DisplayProfile();
}
protected void btnEdit_Click(object sender, EventArgs e)
{
this.EditProfile();
}
protected void btnCancelDisplay_Click(object sender, EventArgs e)
{
this.ResetElements();
}
protected void btnSave_Click(object sender, EventArgs e)
{
this.SaveProfile();
}
protected void btnCancelEdit_Click(object sender, EventArgs e)
{
this.ResetElements();
}
private void DisplayProfile()
{
this.SetElementsForDisplaying();
litfullname.Text = this.Profile.ProfileDetail.FullName;
}
private void EditProfile()
{
this.SetElementsForEditing();
if (Profile.ProfileDetail == null)
{
txtfname.Text = this.Profile.ProfileDetail.FullName;
txtcardno.Text = this.Profile.ProfileDetail.IdentityCardNo;
ddlcardcolor.SelectedValue = this.Profile.ProfileDetail.IdentityCardColour;
txtcardexp.Text = this.Profile.ProfileDetail.IdentityCardExpiryDate.ToString("dd MMMM yyyy");
ddlrace.Text = this.Profile.ProfileDetail.Race;
ddlreligion.SelectedValue = this.Profile.ProfileDetail.Religion;
txtaddress1.Text = this.Profile.ProfileDetail.ContactInformation.Address1;
txtaddress2.Text = this.Profile.ProfileDetail.ContactInformation.Address2;
txtaddress3.Text = this.Profile.ProfileDetail.ContactInformation.Address3;
txtpostcode.Text = this.Profile.ProfileDetail.ContactInformation.Postcode;
ddldistrict.SelectedValue = this.Profile.ProfileDetail.ContactInformation.District;
txtphoneoffice.Text = this.Profile.ProfileDetail.ContactInformation.OfficePhone;
txtphonehome.Text = this.Profile.ProfileDetail.ContactInformation.HomePhone;
txtphonecell.Text = this.Profile.ProfileDetail.ContactInformation.MobilePhone;
txtemail.Text = this.Profile.ProfileDetail.ContactInformation.Email;
}
}
Save profile. This is working properly.
private void SaveProfile()
{
if (Profile.ProfileDetail == null)
{
this.Profile.ProfileDetail.FullName = txtfname.Text;
this.Profile.ProfileDetail.IdentityCardNo = txtcardno.Text;
this.Profile.ProfileDetail.IdentityCardColour = ddlcardcolor.SelectedValue;
this.Profile.ProfileDetail.IdentityCardExpiryDate = DateTime.ParseExact(txtcardexp.Text, "dd MMMM yyyy", null);
this.Profile.ProfileDetail.Race = ddlrace.SelectedValue;
this.Profile.ProfileDetail.Religion = ddlreligion.SelectedValue;
this.Profile.ProfileDetail.ContactInformation.Address1 = txtaddress1.Text;
this.Profile.ProfileDetail.ContactInformation.Address2 = txtaddress2.Text;
this.Profile.ProfileDetail.ContactInformation.Address3 = txtaddress3.Text;
this.Profile.ProfileDetail.ContactInformation.Postcode = txtpostcode.Text;
this.Profile.ProfileDetail.ContactInformation.District = ddldistrict.SelectedValue;
this.Profile.ProfileDetail.ContactInformation.OfficePhone = txtphoneoffice.Text;
this.Profile.ProfileDetail.ContactInformation.HomePhone = txtphonehome.Text;
this.Profile.ProfileDetail.ContactInformation.MobilePhone = txtphonecell.Text;
this.Profile.ProfileDetail.ContactInformation.Email = txtemail.Text;
}
this.Profile.Save();
this.ResetElements();
}
To display, which doesn't work properly
private void SetElementsForDisplaying()
{
pnlDisplayValues.Visible = true;
pnlSetValues.Visible = false;
litUserTitle.Visible = false;
litUserTitle.Text = string.Format("Display profile for {0}", this.Profile.UserName);
}
Edit profile. Working properly
private void SetElementsForEditing()
{
pnlDisplayValues.Visible = false;
pnlSetValues.Visible = true;
litUserTitle.Visible = true;
litUserTitle.Text = string.Format("Edit profile for {0}", this.Profile.UserName);
}
private void ResetElements()
{
pnlSetValues.Visible = false;
pnlDisplayValues.Visible = true;
litUserTitle.Visible = true;
}
private void SetElementsForDisplaying()
{
pnlDisplayValues.Visible = true;
pnlSetValues.Visible = false;
litUserTitle.Visible = true; // set this as visible
litUserTitle.Text = string.Format("Display profile for {0}", this.Profile.UserName);
}
And in your pnlDisplayValues panel add the literals you want and set the values in the DisplayProfile() method

Categories

Resources