NewRow() Method overwritting previous row - c#

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.

Related

Web form is not updating values

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;
}

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);
}

Pass DGV selected rows to 2nd form

I am trying to pass selected rows of a datagridview to a second form. Then select items in a second DGV and pass the information into a table at that point. What I was trying to do is pass the rows in the manner below:
Form1:
private void toolStripLabel1_Click(object sender, EventArgs e)
{
int interestsKey;
interestsKey = Convert.ToInt32(interestsKeyTextBox.Text);
DataGridViewSelectedRowCollection rows = interestAddDataGridView.SelectedRows;
frmDupeAdd AddDupeForm = new frmDupeAdd(interestAddDataGridView.SelectedRows);
AddDupeForm.Show();
}
On form 2 I cannot seem to be able to access dgIntRows. Not sure if this is the correct way to do this or if there is a better way.
Form 2:
public frmDupeAdd(DataGridViewSelectedRowCollection selectedRows)
{
InitializeComponent();
DataGridViewSelectedRowCollection dgIntRows = selectedRows;
}
private void btnAddAdds_Click(object sender, EventArgs e)
{
DataGridViewSelectedRowCollection rows = dgCaseInt.SelectedRows;
dgCaseInt.Columns[4].Visible = false;
dgCaseInt.Columns[5].Visible = false;
foreach (DataGridViewRow row in rows)
{
DataClasses1DataContext db = new DataClasses1DataContext();
int interestkeyint = Convert.ToInt16(row.Cells[4].Value);
InterestAdd newinterestadd = new InterestAdd();
newinterestadd.InterestsKey = interestkeyint;
foreach (DataGridViewRow row in dgIntRows)
{
newinterestadd.CaseNumberKey = (string)row.Cells[5].Value; ;
newinterestadd.streetNum = (string)row.Cells[2].Value;
newinterestadd.Direction = (string)row.Cells[2].Value;
newinterestadd.Add1 = (string)row.Cells[3].Value;
newinterestadd.Suffix = (string)row.Cells[4].Value;
newinterestadd.Unit = (string)row.Cells[5].Value;
newinterestadd.City = (string)row.Cells[6].Value;
newinterestadd.State = (string)row.Cells[7].Value;
newinterestadd.Zip = (string)row.Cells[8].Value;
db.InterestAdds.InsertOnSubmit(newinterestadd);
db.SubmitChanges();
}
}
}
instead of
public frmDupeAdd(DataGridViewSelectedRowCollection selectedRows)
{
InitializeComponent();
DataGridViewSelectedRowCollection dgIntRows = selectedRows;
}
use
private DataGridViewSelectedRowCollection dgIntRows = new DataGridViewSelectedRowCollection ()
public frmDupeAdd(DataGridViewSelectedRowCollection selectedRows)
{
InitializeComponent();
dgIntRows = selectedRows;
}

Refresh listbox after adding

I have a listbox in C# and want it to refresh after I added a new item(which gets opened with a new form dialog)
Here is my code which doesn't work.
private void showAllItems()
{
itemList = Db.getAllItems();
lb_itemList.DataSource = itemList;
}
private void showItemPreview(object sender, EventArgs e)
{
string curItem = lb_itemList.SelectedItem.ToString();
briefPreviewList = Db.getItemBriefPreview(curItem);
string itemInfos = string.Join(",", briefPreviewList.ToArray());
string[] infos = itemInfos.Split(',');
l_itemDB.Text = curItem;
l_CategoryDB.Text = infos[0];
}
private void b_addItem_Click(object sender, EventArgs e)
{
int uid = 1;
AddItem addItemForm = new AddItem(uid);
addItemForm.ShowDialog();
CurrencyManager cm = (CurrencyManager)BindingContext[itemList];
cm.Refresh();
}
I assume when you insert a new item it gets stored into the database, if this is the case then all you need to do is reset the datasource:
private void b_addItem_Click(object sender, EventArgs e)
{
int uid = 1;
AddItem addItemForm = new AddItem(uid);
addItemForm.ShowDialog();
addItemForm.Dispose();
this.showAllItems();
}

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