I am having a real difficulty getting a string that is being returned from a combobox to convert to a double. I have done some research online and I believe that it should be working. I keep getting user exceptions.
Specifically, I am having an issue with the following part of my code:
private void cboBeverage_SelectedIndexChanged(object sender, EventArgs e)
{
string tempString = cboBeverage.SelectedValue.ToString();
double tempPrice = Convert.ToDouble(tempString);
Calculations(tempPrice);
}
Here is my entire code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace JO_BillCalculator
{
public partial class Form1 : Form
{
double subtotal = 0.00;
double tax = 6.875;
double total = 0.00;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Add data to dtBeverage datatable
DataTable dtBeverage = new DataTable();
DataColumn dc1Beverage = new DataColumn("ItemBeverage");
DataColumn dc2Beverage = new DataColumn("PriceBeverage");
dtBeverage.Columns.Add(dc1Beverage);
dtBeverage.Columns.Add(dc2Beverage);
dtBeverage.Rows.Add("", "0.00");
dtBeverage.Rows.Add("Milk", "1.50");
dtBeverage.Rows.Add("Juice", "2.50");
dtBeverage.Rows.Add("Mineral Water", "2.95");
dtBeverage.Rows.Add("Coffee", "1.25");
dtBeverage.Rows.Add("Tea", "1.50");
dtBeverage.Rows.Add("Soda", "1.95");
//Display data in correct combobox
cboBeverage.DataSource = dtBeverage;
cboBeverage.DisplayMember = "ItemBeverage";
cboBeverage.ValueMember = "PriceBeverage";
//Add data to dtAppitizer datatable
DataTable dtAppitizer = new DataTable();
DataColumn dc1Appitizer = new DataColumn("ItemAppitizer");
DataColumn dc2Appitizer = new DataColumn("PriceAppitizer");
dtAppitizer.Columns.Add(dc1Appitizer);
dtAppitizer.Columns.Add(dc2Appitizer);
dtAppitizer.Rows.Add("", "0.00");
dtAppitizer.Rows.Add("Buffalo Wings", "5.95");
dtAppitizer.Rows.Add("Buffalo Fingers", "6.95");
dtAppitizer.Rows.Add("Potato Skins", "8.95");
dtAppitizer.Rows.Add("Nachos", "8.95");
dtAppitizer.Rows.Add("Mushroom Caps", "10.95");
dtAppitizer.Rows.Add("Shrimp Cocktail", "12.95");
dtAppitizer.Rows.Add("Chips and Salsa", "6.95");
//Display data in correct combobox
cboAppetizer.DataSource = dtAppitizer;
cboAppetizer.DisplayMember = "ItemAppitizer";
cboAppetizer.ValueMember = "PriceAppitizer";
//Add data to dtMainCourse datatable
DataTable dtMainCourse = new DataTable();
DataColumn dc1MainCourse = new DataColumn("ItemMainCourse");
DataColumn dc2MainCourse = new DataColumn("PriceMainCourse");
dtMainCourse.Columns.Add(dc1MainCourse);
dtMainCourse.Columns.Add(dc2MainCourse);
dtMainCourse.Rows.Add("", "0.00");
dtMainCourse.Rows.Add("Chicken Alfredo", "13.95");
dtMainCourse.Rows.Add("Chicken Picatta", "13.95");
dtMainCourse.Rows.Add("Turkey Club", "11.95");
dtMainCourse.Rows.Add("Lobster Pie", "19.95");
dtMainCourse.Rows.Add("Prime Rib", "20.95");
dtMainCourse.Rows.Add("Shrimp Scampi", "18.95");
dtMainCourse.Rows.Add("Turkey Dinner", "13.95");
dtMainCourse.Rows.Add("Stuffed Chicken", "14.95");
dtMainCourse.Rows.Add("Seafood Alfredo", "15.95");
//Display data in correct combobox
cboMainCourse.DataSource = dtMainCourse;
cboMainCourse.DisplayMember = "ItemMainCourse";
cboMainCourse.ValueMember = "PriceMainCourse";
//Add data to dtDessert datatable
DataTable dtDessert = new DataTable();
DataColumn dc1Dessert = new DataColumn("ItemDessert");
DataColumn dc2Dessert = new DataColumn("PriceDessert");
dtDessert.Columns.Add(dc1Dessert);
dtDessert.Columns.Add(dc2Dessert);
dtDessert.Rows.Add("", "0.00");
dtDessert.Rows.Add("Apple Pie", "5.95");
dtDessert.Rows.Add("Sundae", "3.95");
dtDessert.Rows.Add("Carrot Cake", "5.95");
dtDessert.Rows.Add("Mud Pie", "4.95");
dtDessert.Rows.Add("Apple Crisp", "5.95");
//Display data in correct combobox
cboDessert.DataSource = dtDessert;
cboDessert.DisplayMember = "ItemDessert";
cboDessert.ValueMember = "PriceDessert";
}
private void cboBeverage_SelectedIndexChanged(object sender, EventArgs e)
{
string tempString = cboBeverage.SelectedValue.ToString();
double tempPrice = Convert.ToDouble(tempString);
Calculations(tempPrice);
}
private void cboAppetizer_SelectedIndexChanged(object sender, EventArgs e)
{
cboAppetizer.SelectedIndex = 0;
}
private void cboMainCourse_SelectedIndexChanged(object sender, EventArgs e)
{
cboMainCourse.SelectedIndex = 0;
}
private void cboDessert_SelectedIndexChanged(object sender, EventArgs e)
{
cboDessert.SelectedIndex = 0;
}
private void Calculations(double price)
{
}
}
}
use selectedItem insted of SelectedValue
DataRow selectedDataRow = ((DataRowView)cboBeverage.SelectedItem).Row;
double tempPrice = Convert.ToDouble(selectedDataRow["PriceBeverage"]);
Calculations(tempPrice);
Related
I've watched a tutorial on youtube that explain how to search in an excel file but when I search for a specific value in a row I must type at the search box column name = 'value at the row' and the column name must be a single word, not 2 words split with space or I must write column name like '%value%' to get similar results.
when I search for a specific value in a row
to search for similar results
column name must be a single word
First: How I can search by writing a specific keyword at any row.
Second: How I can load column names at combo box and search by column name and make it optional to select column.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace excel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnOpen_Click(object sender, EventArgs e)
{
using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel Workbook|*.xlsx",Multiselect = false})
{
if (ofd.ShowDialog() == DialogResult.OK)
{
Cursor.Current = Cursors.WaitCursor;
DataTable dt = new DataTable();
using(XLWorkbook workbook = new XLWorkbook(ofd.FileName))
{
bool isFirstRow = true;
var rows = workbook.Worksheet(1).RowsUsed();
foreach(var row in rows)
{
if (isFirstRow)
{
foreach (IXLCell cell in row.Cells())
dt.Columns.Add(cell.Value.ToString());
isFirstRow = false;
}
else
{
dt.Rows.Add();
int i = 0;
foreach (IXLCell cell in row.Cells())
dt.Rows[dt.Rows.Count - 1][i++] = cell.Value.ToString();
}
}
dataGridView1.DataSource = dt.DefaultView;
lblTotal.Text = $"Total Records:{dataGridView1.RowCount}";
Cursor.Current = Cursors.Default;
}
}
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
try
{
DataView dv = dataGridView1.DataSource as DataView;
if (dv != null)
dv.RowFilter = txtSearch.Text;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
btnSearch.PerformClick();
}
private void label2_Click(object sender, EventArgs e)
{
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
static string ColumnNumberToColumnLetter(int colIndex)
{
int colnum = colIndex;
string columnLetter = null;
int mod = 0;
while (colnum > 0)
{
mod = (colnum - 1) % 26;
columnLetter = (char)(65 + mod) + columnLetter;
colnum = (int)((colnum - mod) / 26);
}
return columnLetter;
}
string columnLetter = ColumnNumberToColumnLetter(27); //return AA
I want to write a program that save all the data from a .csv into a database.
I use a service-based database.
But when I want to use the addtoTablesName like what I used to do and I learned at university, it suddenly throws an error.
This is my code:
class Program
{
static void Main(string[] args)
{
Database1Entities1 dbb = new Database1Entities1();//object database
excel.Application xlApp;
excel.Workbook xlWb;
excel._Worksheet xlWs;
excel.Range xlRange;
excel.Application xlApp1;
excel.Workbook xlWb1;
excel._Worksheet xlWs1;
excel.Range xlRange1;
int rowFile = 0;
int colFile = 0;
string[][] dataFile;
DateTime date = DateTime.Now;
string tgl = date.Date.ToString("dd");
string bln = date.Month.ToString("d2");
string thn = date.Year.ToString();
string tglskrg = thn+bln+tgl;
string[] items;
DateTime otime2 = DateTime.ParseExact(tglskrg, "yyyyMMdd", null);
xlApp = new excel.Application();
string[] filesindirectory = Directory.GetDirectories(#"C:\Users\u532246\Desktop\TRAVELOKA");
foreach (string files in filesindirectory)
{
string name = Path.GetFileName(files);
string subname = name.Substring(10, 8);
DateTime subTime = DateTime.ParseExact(subname, "yyyyMMdd", null);
TimeSpan span = otime2.Subtract(subTime);
if(span.Days < 2)
{
// Console.WriteLine(files);
foreach(string subfiles in Directory.GetFiles(files))
{
xlWb = xlApp.Workbooks.Open(subfiles);
xlWs = xlWb.Sheets[1];
xlRange = xlWs.UsedRange;
rowFile = xlRange.Rows.Count;
colFile = xlRange.Columns.Count;
dataFile = new string[rowFile][];
for(int i = 0; i < dataFile.Length; i++)
{
dataFile[i] = new string[colFile];
}
for(int i = 0; i<rowFile;i++)
{
for(int j = 0; i<colFile;j++)
{
try
{
dataFile[i][j] = xlWs.Cells[i + 1, j + 1].value2.ToString();
//MessageBox.Show(dataMapping[i][j]);
}
catch (Exception ee)
{
dataFile[i][j] = "";
}
}
}
CMRTable cmr = new CMRTable();
for(int i = 0; i < rowFile; i++)
{
items = dataFile[i][0].Split(';');
cmr.Id = i + 1;
cmr.Merchant_Name = items[1];
cmr.Sett_Date = items[2];
cmr.Proc_Date = items[3];
cmr.Mid = items[4];
cmr.CardType = items[5];
cmr.Trx_Date = items[6];
cmr.Jam_Trx = items[7];
cmr.Auth = items[8];
cmr.CardNo = items[9];
cmr.Trx_Type = items[10];
cmr.Amount = items[11];
cmr.Rate = items[12];
cmr.Disc_Amt = items[13];
cmr.Tenor_Ins = items[14];
cmr.Rate_Ins = items[15];
cmr.Disc_Ins = items[16];
cmr.Net_Amt = items[17];
cmr.Purchase_Id = items[18];
cmr.Mechant_Descriptor = items[19];
dbb.AddToCMRTables(cmr); #I CANT USE THIS FUNCTION , DONT KNOW WHY
dbb.SaveChanges();
}
Console.WriteLine(subfiles);
}
}
}
}
}
Can someone help me? I think I already do everything exactly like I did in university ..
EDIT: here's the error I get:
Database1Entities1 does not contain a definition for AddToCMRTables and no accessible extension method AddToCMRTables accepting a first argument of type Database1Entities1 could be found
I copy what i used to do in university (here's the code)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{//dipakai ketika ingin menginsert data ke database.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
displayData();
}
Database1Entities db = new Database1Entities();//object database
private void displayData()
{
var query = from x
in db.MsStudents
select x;
dataGridView1.DataSource = query;
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
txtID.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString();
txtName.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString();
}//buat ngeklik yg ada di data grid view
private void txtSearch_TextChanged(object sender, EventArgs e)
{
search(txtSearch.Text);
}
public void search(string kata) {
var query = from x
in db.MsStudents
where x.Name.Contains(kata)//apa yang muncul di kotak search itu di select
select x;
dataGridView1.DataSource = query;
}//function buat search
private void btnInsert_Click(object sender, EventArgs e)
{
MsStudent student = new MsStudent();
student.ID = Int32.Parse(txtID.Text);
student.Name = txtName.Text;
db.AddToMsStudents(student);
db.SaveChanges();
displayData();
}
private void btnReset_Click(object sender, EventArgs e)
{
foreach (Control a in this.Controls)
{
if (a.GetType() == typeof(TextBox))
{
a.Text = "";
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
By clicking on the "Synchronize" button we will collect the stock numbers of the 2 tables and print them on the stock number of the 1st table.
I have two excel files side by side and I'm having trouble updating them
(addition + transfer).
Synchronize
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Excel;
using Microsoft.Office.Core;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataSet ds;
DataSet ds2;
OpenFileDialog of;
OpenFileDialog ofl;
FileStream fs;
FileStream fst;
IExcelDataReader okuyucu;
IExcelDataReader okuyucu1;
DataTable dt;
DataTable dts;
DataRow new_data_row;
int adet;
int adet2;
int StokNo1;
int StokNo2;
private void button3_Click(object sender, EventArgs e)//Synchronize Button
{
int Adet = Int32.Parse(dataGridView1.Columns[2].Index.ToString());
int Adet2 = Int32.Parse(dataGridView2.Columns[2].Index.ToString());
int StokNo1 = Int32.Parse(dataGridView1.Columns[0].Index.ToString());
int StokNo2 = Int32.Parse(dataGridView2.Columns[0].Index.ToString());
foreach (DataTable dt in ds.Tables)
{
for (int i = 0; i < ds.Tables.Count; i++)
{
StokNo1 = Int32.Parse(dataGridView1.Columns[0].Index.ToString());//The StokNo belonging to DataGridWiew1.
Adet = Int32.Parse(dataGridView1.Columns[2].Index.ToString());//The number belonging to DataGridWiew1.
}
}
foreach (DataTable dt2 in ds2.Tables)
{
for (int j = 0; j < ds2.Tables.Count; j++)
{
StokNo2 = Int32.Parse(dataGridView2.Columns[0].Index.ToString());//The StokNo belonging to DataGridWiew2.
Adet2 = Int32.Parse(dataGridView2.Columns[2].Index.ToString());//The number belonging to DataGridWiew2.
}
}
if ((StokNo1 == StokNo2))//StokNo is Equal
{
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
int toplam = adet + adet2;
ds.Tables[0].Rows.Add(toplam);
}
}
else
{
ds.Tables[0].Rows.Add();//If stokno is not equal add to the last listed
}
}
private void button4_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Excel|*.xls";
save.OverwritePrompt = true;
save.CreatePrompt = true;
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter kayıt = new StreamWriter(save.FileName);
kayıt.WriteLine(dataGridView1.ToString());
kayıt.Close();
}
}
}
}
if the stock number is equal to add to list , I want to update the number according to the stock code I want to add it at the end if the stock code is different
I made an application that uses gmap.net. On the map I have three markers. Now what I'm trying to do is to click on a marker opens a new form, click on the second marker to open another form. This is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GMap.NET;
using GMap.NET.MapProviders;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;
namespace GMap
{
public partial class Form1 : Form
{
GMarkerGoogle marker;
GMapOverlay markerOverlay;
DataTable dt;
int Selekcija = 0;
double LatInicial = 43.1383292506958;
double LngInicial = 20.5198994278908;
double LatTehnicka = 43.1378458151015;
double LngTehnicka = 20.5214631557465;
double LatMedicinska = 43.1324426240355;
double LngMedicinska = 20.5122631788254;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("Opis", typeof(string)));
dt.Columns.Add(new DataColumn("Lat", typeof(double)));
dt.Columns.Add(new DataColumn("Long", typeof(double)));
//Ubacivanje podataka u tabelu
dt.Rows.Add("Gimnazija", LatInicial, LngInicial);
dt.Rows.Add("Tehnicka skola", LatTehnicka, LngTehnicka);
dt.Rows.Add("Medicinska skola", LatMedicinska, LngMedicinska);
dataGridView1.DataSource = dt;
//Vidljivost pojedinih kolona
dataGridView1.Columns[1].Visible = false;
dataGridView1.Columns[2].Visible = false;
gMapControl1.DragButton = MouseButtons.Left;
gMapControl1.CanDragMap = true;
gMapControl1.MapProvider = GMapProviders.GoogleMap;
gMapControl1.Position = new PointLatLng(LatInicial, LngInicial);
gMapControl1.MinZoom = 0;
gMapControl1.MaxZoom = 24;
gMapControl1.Zoom = 17;
gMapControl1.AutoScroll = true;
// Obelezivac
markerOverlay = new GMapOverlay("markers");
marker = new GMarkerGoogle(new PointLatLng(LatInicial, LngInicial),GMarkerGoogleType.green);
markerOverlay.Markers.Add(marker);
//marker.ToolTipMode = MarkerTooltipMode.Always;
marker.ToolTipText = string.Format("Gimnazija: \n Latituda: {0} \n Longituda: {1}", LatInicial, LngInicial);
gMapControl1.Overlays.Add(markerOverlay);
markerOverlay = new GMapOverlay("markers");
marker = new GMarkerGoogle(new PointLatLng(LatTehnicka, LngTehnicka), GMarkerGoogleType.green);
markerOverlay.Markers.Add(marker);
//marker.ToolTipMode = MarkerTooltipMode.Always;
marker.ToolTipText = string.Format("Tehnicka skola: \n Latituda: {0} \n Longituda: {1}", LatTehnicka, LngTehnicka);
gMapControl1.Overlays.Add(markerOverlay);
markerOverlay = new GMapOverlay("markers");
marker = new GMarkerGoogle(new PointLatLng(LatMedicinska, LngMedicinska), GMarkerGoogleType.green);
markerOverlay.Markers.Add(marker);
//marker.ToolTipMode = MarkerTooltipMode.Always;
marker.ToolTipText = string.Format("Medicinska skola: \n Latituda: {0} \n Longituda: {1}", LatMedicinska, LngMedicinska);
gMapControl1.Overlays.Add(markerOverlay);
}
private void button1_Click(object sender, EventArgs e)
{
dt.Rows.Add(txtOpis.Text, txtLatituda.Text, txtLongituda.Text);
}
private void SelekcijaSkole(object sender, DataGridViewCellMouseEventArgs e)
{
Selekcija = e.RowIndex;
txtOpis.Text = dataGridView1.Rows[Selekcija].Cells[0].Value.ToString();
txtLatituda.Text = dataGridView1.Rows[Selekcija].Cells[1].Value.ToString();
txtLongituda.Text = dataGridView1.Rows[Selekcija].Cells[2].Value.ToString();
marker.Position = new PointLatLng(Convert.ToDouble(txtLatituda.Text), Convert.ToDouble(txtLongituda.Text));
gMapControl1.Position = marker.Position;
}
private void gMapControl1_MouseDoubleClick(object sender, MouseEventArgs e)
{
double lat = gMapControl1.FromLocalToLatLng(e.X, e.Y).Lat;
double lng = gMapControl1.FromLocalToLatLng(e.X, e.Y).Lng;
txtLatituda.Text = lat.ToString();
txtLongituda.Text = lng.ToString();
marker.Position = new PointLatLng(lat, lng);
marker.ToolTipText = string.Format("Koordinate: \n Latituda {0} \n Longituda {1}", lat, lng);
}
private void button2_Click(object sender, EventArgs e)
{
dataGridView1.Rows.RemoveAt(Selekcija);
}
private void button3_Click(object sender, EventArgs e)
{
gMapControl1.MapProvider = GMapProviders.GoogleChinaSatelliteMap;
}
private void button4_Click(object sender, EventArgs e)
{
gMapControl1.MapProvider = GMapProviders.GoogleMap;
}
private void button5_Click(object sender, EventArgs e)
{
gMapControl1.MapProvider = GMapProviders.GoogleTerrainMap;
}
private void gMapControl1_OnMarkerClick(GMapMarker item, MouseEventArgs e)
{
}
}
}
The gMapControl has a event called OnMarkerClick that you can subscribe to to listen for click events on your makers. You can right click your GmapControl and then select properties. Then Click the lightening bolt button and that will list your events and in there is a OnMarkerClick Event you can double click it and it will build a event handler for you, or you can set it like so.
gMapControl1.OnMarkerClick += (marker, mouseArgs) =>
{
// From this point marker is the clicked marker do as you wish here
// Pass it to another form and use form.show to display the form.
// MessageBox.Show is to show proof the event fired.
MessageBox.Show(marker.ToolTipText);
// If you have a marker form you can display it like so.
MarkerForm form = new MarkerForm();
form.Show();
};
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?