Web form is not updating values - c#

I am trying to save retrieve and update data table from s single web form. Data is saved and retrieve correctly but is not updated.
Here is the code
using System;
using System.Web.UI;
using System.Data;
public partial class Basic_Information : System.Web.UI.Page
{
DataTable user_dt, personal_dt = new DataTable();
string u_id;
Boolean check = false;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
if (Session["user"] != null)
load();
}
protected void btn_save_Click(object sender, EventArgs e)
{
if(check == false)
savedata();
else
editdata();
}
protected void load()
{
user_dt = (DataTable)Session["user"];
u_id = user_dt.Rows[0][0].ToString();
personal_dt = (DataTable)Session["personal"];
if (personal_dt.Rows.Count != 0)
{
retrivedata();
check = true;
}
}
protected void savedata()
{
personal_dt.Columns.Add("User_id");
personal_dt.Columns.Add("Name");
personal_dt.Columns.Add("Father_Name");
personal_dt.Columns.Add("CNIC");
personal_dt.Columns.Add("Date_of_Birth");
personal_dt.Columns.Add("Domicile");
personal_dt.Columns.Add("Gender");
personal_dt.Columns.Add("Religion");
personal_dt.Columns.Add("Nationality");
personal_dt.Columns.Add("Marital");
DataRow per_row = personal_dt.NewRow();
per_row["User_id"] = u_id;
per_row["Name"] = txt_name.Text;
per_row["Father_Name"] = txt_fname.Text;
per_row["CNIC"] = txt_cnic.Text;
per_row["Date_of_Birth"] = txt_dofb.Text;
per_row["Domicile"] = ddl_domicil.SelectedItem.Text;
per_row["Gender"] = ddl_gender.SelectedItem.Text;
per_row["Religion"] = ddl_religion.SelectedItem.Text;
per_row["Nationality"] = txt_nationality.Text;
per_row["Marital"] = ddl_marital.SelectedItem.Text;
personal_dt.Rows.Add(per_row);
string script = "alert('Profile Successfully Saved');";
ClientScript.RegisterStartupScript(this.GetType(), "saved", script, true);
}
}
protected void retrivedata()
{
txt_name.Text = personal_dt.Rows[0]["Name"].ToString();
txt_fname.Text = personal_dt.Rows[0]["Father_Name"].ToString();
txt_cnic.Text = personal_dt.Rows[0]["CNIC"].ToString();
txt_dofb.Text = personal_dt.Rows[0]["Date_of_Birth"].ToString();
ddl_domicil.Items.FindByText(personal_dt.Rows[0] ["Domicile"].ToString()).Selected = true;
ddl_gender.Items.FindByText(personal_dt.Rows[0]["Gender"].ToString()).Selected = true;
ddl_religion.Items.FindByText(personal_dt.Rows[0]["Religion"].ToString()).Selected = true;
txt_nationality.Text = personal_dt.Rows[0]["Nationality"].ToString();
ddl_marital.Items.FindByText(personal_dt.Rows[0]["Marital"].ToString()).Selected = true;
}
protected void editdata()
{
personal_dt.Rows[0]["Name"] = txt_name.Text;
personal_dt.Rows[0]["Father_Name"] = txt_fname.Text;
personal_dt.Rows[0]["CNIC"] = txt_cnic.Text;
personal_dt.Rows[0]["Date_of_Birth"] = txt_dofb.Text;
personal_dt.Rows[0]["Domicile"] = ddl_domicil.SelectedItem.Text;
personal_dt.Rows[0]["Gender"] = ddl_gender.SelectedItem.Text;
personal_dt.Rows[0]["Religion"] = ddl_religion.SelectedItem.Text;
personal_dt.Rows[0]["Nationality"] = txt_nationality.Text;
personal_dt.Rows[0]["Marital"] = ddl_marital.SelectedItem.Text;
}
}
Saving data correctly, retrieving data correctly.
But bug in editing data return the first values which are retrieved.
Also an error that Dropdown cannot select multiple items

Regarding dropdown binding issue, before
Dropdown.DataSource = YourDataSource
add
Dropdown.ClearSelection();

Try this.After filling data to datatable you need to pass that datatable, and update record.
protected void editdata()
{
DataRow dr = personal_dt.NewRow();
personal_dt.Rows.Add(dr);
dr["Name"] = txt_name.Text;
dr["Father_Name"] = txt_fname.Text;
dr["CNIC"] = txt_cnic.Text;
dr["Date_of_Birth"] = txt_dofb.Text;
dr["Domicile"] = ddl_domicil.SelectedItem.Text;
dr["Gender"] = ddl_gender.SelectedItem.Text;
dr["Religion"] = ddl_religion.SelectedItem.Text;
dr["Nationality"] = txt_nationality.Text;
dr["Marital"] = ddl_marital.SelectedItem.Text;
}

Related

c# Windows Form slow rendering objects

I have spent some time designing my first project using C#, it is a Windows form project with 8 buttons on the side. pressing one of the buttons will open another form within the parent form as a window. On clicking the button the new form loads up about 27 objects mostly Labels, Textboxes, Comboboxes and a few DateTimePickers. For some reason it you can see it drawing the boxes and it looks slow. I have an SQL db included with my project which is tiny and contains only 2 rows of data. It is very dishearting to spend all that time working on it only to see it run like a ZX Spectrum. I am using Microsoft Visual Studio 2019 and is fully updated. I have no errors, no warnings thank god but the performance is horrible. One of the comboBoxes when selected will make visible 3 more textBoxes and even making those visible is really slow. Is there something I am doing wrong or is there a way to have it working faster please?
This is the code of my childForm which opens from the main parentForm, sorry is is a bit long but it is all of it.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace AvianManager.Forms
{
public partial class formMyBirds : Form
{
SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Dion\Documents\AvianManager.mdf;Integrated Security=True;Connect Timeout=30");
public formMyBirds()
{
InitializeComponent();
}
private void formMyBirds_Load(object sender, EventArgs e)
{
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
var form = Application.OpenForms["formMyBirdsHelper"]; // Lookup form and check if already open
if (form == null)
{
formMyBirdsHelper MyBirdsHelper = new formMyBirdsHelper(); // Instantiate a FormMyBirdsHelp object.
MyBirdsHelper.Show(); // Show FormMyBirdsHelp and
}
}
private void comboBoxLegBandType_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxLegBandType.GetItemText(this.comboBoxLegBandType.SelectedItem);
if (selected != "None" || selected == null)
{
textBoxLegBandID.Visible = true;
labelLegBandId.Visible = true;
textBoxLegBandSize.Visible = true;
labelLegBandSize.Visible = true;
}
else
{
textBoxLegBandID.Visible = false;
labelLegBandId.Visible = false;
textBoxLegBandSize.Visible = false;
labelLegBandSize.Visible = false;
}
}
private void comboBoxPrevOwner_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxPrevOwner.GetItemText(this.comboBoxPrevOwner.SelectedItem);
if (selected != "No")
{
textBoxLastOwnerName.Visible = true;
labelLastOwnerName.Visible = true;
textBoxLastOwnerFone.Visible = true;
labelLastOwnerFone.Visible = true;
textBoxLastOwnerAddr.Visible = true;
labelLastOwnerAddr.Visible = true;
}
else
{
textBoxLastOwnerName.Visible = false;
labelLastOwnerName.Visible = false;
textBoxLastOwnerFone.Visible = false;
labelLastOwnerFone.Visible = false;
textBoxLastOwnerAddr.Visible = false;
labelLastOwnerAddr.Visible = false;
}
}
private void comboBoxVitalStatus_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxVitalStatus.GetItemText(this.comboBoxVitalStatus.SelectedItem);
if (selected != "Alive")
{
dateTimeDateOfDeath.Visible = true;
labelDateOfDeath.Visible = true;
textBoxCauseOfDeath.Visible = true;
labelCauseOfDeath.Visible = true;
}
else
{
dateTimeDateOfDeath.Visible = false;
labelDateOfDeath.Visible = false;
textBoxCauseOfDeath.Visible = false;
labelCauseOfDeath.Visible = false;
}
}
private void comboBoxRetained_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxRetained.GetItemText(this.comboBoxRetained.SelectedItem);
if (selected != "Yes")
{
dateTimeRelinquishedDate.Visible = true;
labelRelinquishedDate.Visible = true;
}
else
{
dateTimeRelinquishedDate.Visible = false;
labelRelinquishedDate.Visible = false;
}
}
private void textBoxUid_TextChanged(object sender, EventArgs e)
{
SqlCommand cmd1 = new SqlCommand("select top 1 * from dbMyBirds where db_Uid = '" + textBoxUid.Text + "'", connection);
cmd1.Parameters.AddWithValue("db_Uid", textBoxUid.Text);
SqlDataReader reader1;
connection.Open();
reader1 = cmd1.ExecuteReader();
if (reader1.Read())
{
labelResult.Text = "Found";
textBoxName.Text = reader1["db_Name"].ToString();
textBoxSpecies.Text = reader1["db_Species"].ToString();
comboBoxLegBandType.Text = reader1["db_LegBandType"].ToString();
textBoxLegBandID.Text = reader1["db_LegBandId"].ToString();
textBoxLegBandSize.Text = reader1["db_LegBandSize"].ToString();
comboBoxPrevOwner.Text = reader1["db_PrevOwner"].ToString();
textBoxLastOwnerName.Text = reader1["db_PrevOwnerName"].ToString();
textBoxLastOwnerFone.Text = reader1["db_PrevOwnerFone"].ToString();
textBoxLastOwnerAddr.Text = reader1["db_PrevOwnerAddr"].ToString();
comboBoxIsHybrid.Text = reader1["db_Hybrid"].ToString();
comboBoxRearedBy.Text = reader1["db_RearedBy"].ToString();
textBoxDisformaties.Text = reader1["db_Disformaties"].ToString();
comboBoxVitalStatus.Text = reader1["db_VitalStatus"].ToString();
dateTimeDateOfDeath.Text = reader1["db_DateDied"].ToString();
textBoxCauseOfDeath.Text = reader1["db_CauseOfDeath"].ToString();
comboBoxRetained.Text = reader1["db_Retained"].ToString();
dateTimeRelinquishedDate.Text = reader1["db_RelinquishedDate"].ToString();
dateTimeHatchDate.Text = reader1["db_HatchDate"].ToString();
dateTimeFledgeDate.Text = reader1["db_FledgeDate"].ToString();
comboBoxMaleParentHybrid.Text = reader1["db_MPisHybrid"].ToString();
textBoxMaleParentId.Text = reader1["db_MPUid"].ToString();
textBoxMaleParentSpecies.Text = reader1["db_MPSpecies"].ToString();
comboBoxHenParentHybrid.Text = reader1["db_FPisHybrid"].ToString();
textBoxHenParentId.Text = reader1["db_FPUid"].ToString();
textBoxHenParentSpecies.Text = reader1["db_FPSpecies"].ToString();
textBoxNotes.Text = reader1["db_Notes"].ToString();
}
else
{
resetInputs();
if (textBoxUid.Text == "")
{
labelResult.Text = "Live Search";
}
else
{
labelResult.Text = "Nothing Found";
}
}
connection.Close();
}
//Reset input fields if no results
private void resetInputs()
{
string dt2;
DateTime date2 = DateTime.Now;
dt2 = date2.ToShortDateString(); // display format: 15/07/2021
textBoxName.Text = "";
textBoxSpecies.Text = "";
comboBoxLegBandType.Text = "Select";
textBoxLegBandID.Text = "";
textBoxLegBandSize.Text = "";
comboBoxPrevOwner.Text = "Select";
textBoxLastOwnerName.Text = "";
textBoxLastOwnerFone.Text = "";
textBoxLastOwnerAddr.Text = "";
comboBoxIsHybrid.Text = "Select";
comboBoxRearedBy.Text = "Select";
textBoxDisformaties.Text = "";
comboBoxVitalStatus.Text = "Select";
dateTimeDateOfDeath.Text = dt2;
textBoxCauseOfDeath.Text = "";
comboBoxRetained.Text = "Select";
dateTimeRelinquishedDate.Text = dt2;
dateTimeHatchDate.Text = dt2;
dateTimeFledgeDate.Text = dt2;
comboBoxMaleParentHybrid.Text = "Select";
textBoxMaleParentId.Text = "";
textBoxMaleParentSpecies.Text = "";
comboBoxHenParentHybrid.Text = "Select";
textBoxHenParentId.Text = "";
textBoxHenParentSpecies.Text = "";
textBoxNotes.Text = "";
}
private void buttonInsert_Click(object sender, EventArgs e)
{
}
}
}

NewRow() Method overwritting previous row

I have a form that adds rows into a datatable. So i create the datatable:
DataTable vendas = new DataTable();
Then on Page_Load it creates the Columns:
vendas.Columns.Add("Nome");
vendas.Columns.Add("Morada");
vendas.Columns.Add("Contribuinte");
vendas.Columns.Add("CC");
vendas.Columns.Add("Email");
vendas.Columns.Add("Agregado");
vendas.Columns.Add("Banco");
vendas.Columns.Add("IBAN");
vendas.Columns.Add("Produtos");
And then inside the submit form (button action) it adds the form values as a new row and binds them to a Gridview:
protected void x(object sender, EventArgs e)
{
DataRow venda = vendas.NewRow();
venda["Nome"] = nomecliente;
venda["Morada"] = moradacliente;
venda["Contribuinte"] = contribuintecliente;
venda["CC"] = cccliente;
venda["Email"] = mailcliente;
venda["Agregado"] = agregadocliente;
venda["Banco"] = bancocliente;
venda["IBAN"] = ibancliente;
venda["Produtos"] = produtocliente;
vendas.Rows.Add(venda);
GridviewVendas.DataSource = vendas;
GridviewVendas.DataBind();
}
What is happening tho is that each time it runs this last method it overwrites the previous row instead of adding a new one. I'm doing something wrong and it's probably a dumb mistake but i'm just not seeing it.
EDIT: Here is all that in one:
public partial class _Default : System.Web.UI.Page
{
public string nome;
public string planosaudeantigo;
public string valorplanosaudeantigo;
public string condicoesplanosaudeantigo;
public string stringagregadofamiliar;
public string nomecliente;
public string moradacliente;
public string contribuintecliente;
public string cccliente;
public string mailcliente;
public string agregadocliente;
public string bancocliente;
public string ibancliente;
public string produtocliente;
DataTable vendas = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
vendas.Columns.Add("Nome");
vendas.Columns.Add("Morada");
vendas.Columns.Add("Contribuinte");
vendas.Columns.Add("CC");
vendas.Columns.Add("Email");
vendas.Columns.Add("Agregado");
vendas.Columns.Add("Banco");
vendas.Columns.Add("IBAN");
vendas.Columns.Add("Produtos");
}
protected void InserirVenda_Click(object sender, EventArgs e)
{
nomecliente = NomeCliente.Text;
moradacliente = MoradaCliente.Text;
contribuintecliente = ContribuinteCliente.Text;
cccliente = CCCliente.Text;
mailcliente = MailCliente.Text;
agregadocliente = AgregadoCliente.Text;
bancocliente = BancoCliente.Text;
ibancliente = IbanCliente.Text;
for (int i = 0; i < ProdutosCliente.Items.Count; i++)
{
if (ProdutosCliente.Items[i].Selected)
{
produtocliente += ProdutosCliente.Items[i].Value + ",";
}
}
DataRow venda = vendas.NewRow();
venda["Nome"] = nomecliente;
venda["Morada"] = moradacliente;
venda["Contribuinte"] = contribuintecliente;
venda["CC"] = cccliente;
venda["Email"] = mailcliente;
venda["Agregado"] = agregadocliente;
venda["Banco"] = bancocliente;
venda["IBAN"] = ibancliente;
venda["Produtos"] = produtocliente;
vendas.Rows.Add(venda);
GridviewVendas.DataSource = vendas;
GridviewVendas.DataBind();
}
}
You do it like this:
protected void Page_Load(object sender, EventArgs e)
{
//check if it is a postback
if (!Page.IsPostBack)
{
//create a new table
DataTable vendas = new DataTable();
//add some columns
vendas.Columns.Add("Nome");
vendas.Columns.Add("Morada");
//add the datatable to the viewstate
ViewState["vendas"] = vendas;
}
else
{
//check if the viewstate exits and cast it back to a datatable
if (ViewState["vendas"] != null)
{
vendas = ViewState["vendas"] as DataTable;
}
}
}
And now you can keep adding rows in InserirVenda_Click
Variables are not persisted between postbacks, your DataTable gets reinitialised every time the Page_Load.
You can use Session variables or cookies to persist your data.

How to get data from SQL database to store in to a combo box - C#

How can i get the value of outlet ID it on a comboBox?
here is my code to getting the values from Database and store it on a combobox.
public partial class Addstock : Form
{
String connectionString = ConfigurationManager.ConnectionStrings["TCConnectionString"].ConnectionString;
List<BOStockTransfer> StockList = new List<BOStockTransfer>();
int updateIndex = -1;
public Addstock()
{
InitializeComponent();
}
private void Addstock_Load(object sender, EventArgs e)
{
loadstock();
GetOutlets();
Getproduct();
GetGetWH();
cmdoutletID.Visible = false;
lbloutid.Visible = false;
cmdwh.Visible = false;
lblwh.Visible = false;
}
private void GetOutlets()
{
BOStockTransfer obj_StockTransfer = new BOStockTransfer();
DataSet ds_OutletList = obj_StockTransfer.GetOutlets(connectionString);
if (ds_OutletList.Tables[0].Rows.Count != 0)
{
cmdoutletID.DataSource = ds_OutletList.Tables[0];
cmdoutletID.DisplayMember = "outletId";
}
}
Thank you for your help!
you are setting :
cmdoutletID.Visible = false;
what makes the combobox invisible
you have to set it as follows :
cmdoutletID.Visible = true;
After you added the images , the column name is outletID and Not outletId
so change your code as follows :
private void GetOutlets()
{
BOStockTransfer obj_StockTransfer = new BOStockTransfer();
DataSet ds_OutletList = obj_StockTransfer.GetOutlets(connectionString);
if (ds_OutletList.Tables[0].Rows.Count != 0)
{
cmdoutletID.DataSource = ds_OutletList.Tables[0];
cmdoutletID.DisplayMember = "outletID";
cmdoutletID.ValueMember = "outletID";
cmdoutletID.Enabled = true;
}
}
The combo box has two properties which determine where it loads data from:
DisplayMember
ValueMember
The "ValueMember" property defines which named field populates the ListItem's "ValueProperty". That way, when you do combobox.SelectedItem.Value, you will get the value stored in the named field you specified for "ValueProperty".
Assuming that you are certain that your query is returning rows, perhaps try adding the items "manually" rather than relying on automatic databinding.
private void GetOutlets()
{
BOStockTransfer obj_StockTransfer = new BOStockTransfer();
DataSet ds_OutletList = obj_StockTransfer.GetOutlets(connectionString);
cmdoutletID.DisplayMember = "outletId";
cmdoutletID.ValueMember = "pkID";
cmdoutletID.BeginUpdate();
try
{
cmdoutletID.Items.Clear();
foreach (var row in ds_OutletList.Tables[0].Rows)
cmdoutletID.Items(new { outletid = row["outletid"], pkID = row["primaryKeyIDFieldName"] });
}
finally { cmdoutletID.EndUpdate(); }
}
Try this:
BOStockTransfer obj_StockTransfer = new BOStockTransfer();
DataSet ds_OutletList = obj_StockTransfer.GetOutlets(connectionString);
if (ds_OutletList.Tables[0].Rows.Count != 0)
{
cmdoutletID.DataSource = ds_OutletList.Tables[0];
cmdoutletID.DisplayMember = "outletname";
cmdoutletID.ValueMember = "outletId";
}
To capture selected value, for example on button click:
protected button1_Click(object o, EventArgs e)
{
var selectedId = cmboutletID.SelectedValue;
MessageBox.Show(selectedId);
}

Datatable is being overwritten

In an ASP.NET project i have 2 textboxes and a submit button.
In the event handler of button clicked i want to save the values of the textboxes to a datatable and then bind the datatable to a Gridview.
This has to happen multiple times. But every time the datatable has one row, like being overwritten every time the event handler fires. It's like the datatable is being created from the beginning every time the event handler fires. Code below. Thanks for your time.
EDIT: Thanks for all the answers you gave.
protected void BtnInsertCustomerLegalRelationsInsert_Click(object sender, EventArgs e)
{
string FullCompanyName = TbxFullCompanyName.Text.Trim();
object LegalRelationAfm = TbxLegalRelationAfm.Text.Trim();
if (dtCustomersLegalRelations.Columns.Count == 0)
{
dtCustomersLegalRelations.Columns.Add("FullCompanyName",typeof(string));
dtCustomersLegalRelations.Columns.Add("LegalRelationAfm",typeof(string));
}
DataRow dr = dtCustomersLegalRelations.NewRow();
dr["FullCompanyName"] = FullCompanyName;
dr["LegalRelationAfm"] = LegalRelationAfm;
dtCustomersLegalRelations.Rows.Add(dr);
GvCustomerRegalRelations.DataSource = dtCustomersLegalRelations;
GvCustomerRegalRelations.DataBind();
}
The whole code behind here
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class ConnectedBorrowers_CustomerBasicInput : System.Web.UI.UserControl
{
DataTable dtCustomersLegalRelations = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TrLegalRelations1.Visible = TrLegalRelations2.Visible = TrLegalRelations3.Visible = false;
}
}
protected void CbMandatoryAFM_CheckedChanged(object sender, EventArgs e)
{
if (CbMandatoryAFM.Checked == true)
{
TbxCustAfm.ReadOnly = true;
TbxCustAfm.BackColor = Color.LightGray;
}
else
{
TbxCustAfm.ReadOnly = false;
TbxCustAfm.BackColor = Color.White;
}
}
protected void CbLegalRelationsMandatoryAFM_CheckedChanged(object sender, EventArgs e)
{
if (CbLegalRelationsMandatoryAFM.Checked == true)
{
TbxLegalRelationAfm.ReadOnly = true;
TbxLegalRelationAfm.BackColor = Color.LightGray;
}
else
{
TbxLegalRelationAfm.ReadOnly = false;
TbxLegalRelationAfm.BackColor = Color.White;
}
}
protected void CbLegalRelations_CheckedChanged(object sender, EventArgs e)
{
if (CbLegalRelations.Checked == true)
{
TrLegalRelations1.Visible = TrLegalRelations2.Visible = TrLegalRelations3.Visible = true;
}
else
{
TrLegalRelations1.Visible = TrLegalRelations2.Visible = TrLegalRelations3.Visible = false;
}
}
protected void BtnInsertCustomerLegalRelationsInsert_Click(object sender, EventArgs e)
{
try
{
string FullCompanyName = TbxFullCompanyName.Text.Trim();
object LegalRelationAfm = TbxLegalRelationAfm.Text.Trim();
if (dtCustomersLegalRelations.Columns.Count == 0)
{
dtCustomersLegalRelations.Columns.Add("FullCompanyName",typeof(string));
dtCustomersLegalRelations.Columns.Add("LegalRelationAfm",typeof(string));
}
DataRow dr = dtCustomersLegalRelations.NewRow();
dr["FullCompanyName"] = FullCompanyName;
dr["LegalRelationAfm"] = LegalRelationAfm;
dtCustomersLegalRelations.Rows.Add(dr);
GvCustomerRegalRelations.DataSource = dtCustomersLegalRelations;
GvCustomerRegalRelations.DataBind();
}
catch (Exception ex)
{
((Label)this.Page.Master.FindControl("LblError")).Text = ex.Message;
}
}
Try such approach:
public partial class ConnectedBorrowers_CustomerBasicInput : System.Web.UI.UserControl
{
DataTable dtCustomersLegalRelations;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dtCustomersLegalRelations = new DataTable();
Session["table"] = dtCustomersLegalRelations;
TrLegalRelations1.Visible = TrLegalRelations2.Visible = TrLegalRelations3.Visible = false;
} else {
dtCustomersLegalRelations = Session["table"] as DataTable;
}
}
...
}
The value of 'dtCustomersLegalRelations' will not persist through PostBack events - so when you add the row on the end of it, you're doing so on a new instance.
You need to fetch all the data back out of the GridView before you add the new row and re-bind it.
st4hoo's answer above should sort it for you.
When u click the button postback occurs. During each postback your datatable is created from the beginning. So u will lose ur old data.
So one option is that u can keep the datatable with data in a session and retrieve the datatable from the session during the next button click and add the new row.
At what point do you create the datatable (dtCustomersLegalRelations)? Could you paste the complete code including the cration of the datatable and the button_click?

List box pops back to the first item after SelectedIndexChange event fires

I have a 3 dropdownlist control with a selectedindexchanged event that fires correctly. However, when you select an item from the list the index value that is returned to the selectedindexchanged event does not change; the list box pops back to the first item in the list. Any help would be appreciated. ~Dharmendra~
`public partial class Production : System.Web.UI.Page
{
EmployeeQuotientCL.Production _production = null;
DataSet dsNatureOfWork = new DataSet();
DataSet dsProjectRegion = new DataSet();
DataSet dsCountyDetails = new DataSet();
DataSet dsWorkType = new DataSet();
DataSet dsTask = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string userEcode=Convert.ToString(Session["UserID"]);
_production = new EmployeeQuotientCL.Production();
dsNatureOfWork = _production.GetNatureOfWork();
if (dsNatureOfWork.Tables[0].Rows.Count > 0)
{
BindDdlNatureOfWork(dsNatureOfWork);
}
else
{
}
}
}
public void BindDdlNatureOfWork(DataSet dsNatureOfWork)
{
ddlNatureofWork.DataSource = dsNatureOfWork.Tables[0];
ddlNatureofWork.DataTextField = "NatureOfWorkName";
ddlNatureofWork.DataValueField = "NatureOfWorkID";
ddlNatureofWork.DataBind();
ddlNatureofWork.Items.Insert(0, "--Select Nature of Work--");
}
public void FillRegionProject(int NatureOfWorkID)
{
if ((NatureOfWorkID != null) || (NatureOfWorkID != 0))
{
_production = new EmployeeQuotientCL.Production();
dsProjectRegion = _production.GetProjectRegion(NatureOfWorkID);
if (dsProjectRegion.Tables[0].Rows.Count > 0)
{
ddlRegionProjectName.DataSource = dsProjectRegion.Tables[0];
ddlRegionProjectName.DataTextField = "RegionProjectName";
ddlRegionProjectName.DataValueField = "RegionProjectID";
ddlRegionProjectName.DataBind();
ddlRegionProjectName.Items.Insert(0, "--Select Region/Project--");
}
else
{
}
}
}
protected void ddlRegionProjectName_SelectedIndexChanged(object sender, EventArgs e)
{
int RegionProjectID = Convert.ToInt32(ddlRegionProjectName.SelectedValue.ToString());
FillCounty(RegionProjectID);
ddlRegionProjectName.SelectedIndex = 0;
}
public void FillCounty(int regionprojectID)
{
if ((regionprojectID != null) || (regionprojectID != 0))
{
_production = new EmployeeQuotientCL.Production();
dsCountyDetails = _production.GetCounty(regionprojectID);
if (dsCountyDetails.Tables[0].Rows.Count > 0)
{
ddlCountyName.DataSource = dsCountyDetails.Tables[0];
ddlCountyName.DataTextField = "CountyName";
ddlCountyName.DataValueField = "CountyID";
ddlCountyName.DataBind();
ddlCountyName.Items.Insert(0, "--Select County--");
}
else
{
}
}
}
protected void ddlNatureofWork_SelectedIndexChanged(object sender, EventArgs e)
{
int NowID = Convert.ToInt32(ddlNatureofWork.SelectedValue.ToString());
FillRegionProject(NowID);
ddlRegionProjectName.SelectedIndex = 0;
}
}
}`
You are doing ddlRegionProjectName.SelectedIndex = 0; in every SelectedIndexChanged event.
You have no event for ddlCountyName control in the code shared by you.

Categories