Im facing a very weird issue, wich should be very simple.
What im trying to achieve: I have 2 datagrids: 1 with invoiceheaders and 1 with invoiceDetails.
When i click on a particular row from the invoiceheaders, the invoicedetails need to change and show the particular details of that invoice. The event im using for this is dgvInvoiceHeaders_SelectionChanged.
So the code in the view:
private void InvoiceListView_Load(object sender, EventArgs e)
{
int invoiceId = 1;
invoiceHeadersBinding.DataSource = invoiceListPresenter.getInvoiceHeaders();
dgvInvoiceHeaders.DataSource = invoiceHeadersBinding;
setInvoiceHeaderColumns();
if (dgvInvoiceHeaders.CurrentRow != null)
{
Int32.TryParse(dgvInvoiceHeaders.CurrentRow.Cells[0].FormattedValue.ToString(), out invoiceId);
}
dgvInvoiceDetails.DataSource = invoiceListPresenter.getSelectedInvoiceDetails(invoiceId);
dgvInvoiceDetails.DataSource = invoiceListPresenter.invoiceDetails;
setInvoiceDetailColumns();
}
private void dgvInvoiceHeaders_SelectionChanged(object sender, EventArgs e)
{
dgvInvoiceDetails.DataSource = invoiceListPresenter.getSelectedInvoiceDetails(Convert.ToInt32(dgvInvoiceHeaders.CurrentRow.Cells[0].FormattedValue.ToString()));
dgvInvoiceDetails.DataSource = invoiceListPresenter.invoiceDetails;
setInvoiceDetailColumns();
}
And this is the code of the methods im calling:
public List<tbl_invoices> invoiceHeaders;
public BindingList<tbl_invoices> getInvoiceHeaders()
{
try
{
using (var invoices = new DBCrownfishEntities())
{
invoices.Configuration.LazyLoadingEnabled = false;
var invoice = from i in invoices.tbl_invoices
select i;
invoiceHeaders = invoice.ToList();
var listBinding = new BindingList<tbl_invoices>(invoiceHeaders);
return listBinding;
}
}
catch (Exception exe)
{
throw exe;
}
}
public List<tbl_invoiceDetail> invoiceDetails;
public BindingList<tbl_invoiceDetail> getSelectedInvoiceDetails(int invoiceID)
{
try
{
using (var invoices = new DBCrownfishEntities())
{
invoices.Configuration.LazyLoadingEnabled = false;
var invoiceDetail = from i in invoices.tbl_invoiceDetail
where i.InvoiceID == invoiceID
select i;
invoiceDetails = invoiceDetail.ToList();
var listBinding = new BindingList<tbl_invoiceDetail>(invoiceDetails);
return listBinding;
}
}
catch (Exception exe)
{
throw exe;
}
}
But with this example the formload is loaded correctly. But after the event is fired, my invoiceheader datagrid is empty. When i put the text in comment at the method dgvInvoiceHeaders_selectionChanged(), I see that both of the datagrids are filled correctly.
A push in the right direction would be very kind.
Related
I have a form. Which contains 2 tab.
First Tab is for instance Team1 info, where you can select player from datagridview. Selected player's info will populate in designated textboxes.
In tab 2 Team2, and exactly same concept.
I do use same exactly code to update Team 1(Tab1) player's info,and I works. But not for Team 2(Tab 2) player's.
This is screen shot of my code[![enter image description here][1]][1]
Team 1
private void updateButton_Click(object sender, EventArgs e)
{
//Local Variable
int barID = 0;
if (team1DataGridView.CurrentRow != null)
{
//Get row index
int rowIndex = team1DataGridView.CurrentRow.Index;
//Pass to local Variable
barID = Convert.ToInt32(team1DataGridView.Rows[rowIndex].Cells[0].Value);
}
var updatePlayers = (from p in _dbContext.barcelonaTeams
where p.ID == barID
select p).SingleOrDefault();
if (updatePlayers != null)
{
updatePlayers.LastName = lastNameTextBox.Text;
updatePlayers.FirstName = firstNameTextBox.Text;
updatePlayers.Phone = cellNumberTextBox.Text;
updatePlayers.PlayersPosition = playerPositionComboBox.Text;
}
try
{
//Submit Changes
_dbContext.SubmitChanges();
//Refresh datagridview'
team1DataGridView.Refresh();
}
catch (Exception exception)
{
//Display an error message
MessageBox.Show(exception.Message);
}
}
Team 2
private void mUpdateButton_Click(object sender, EventArgs e)
{
//Local variable
int barID = 0;
if (team2DataGridView.CurrentRow != null)
{
//Get row index
int rowIndex = team2DataGridView.CurrentRow.Index;
//Pass to local Variable
barID = Convert.ToInt32(team2DataGridView.Rows[rowIndex].Cells[0].Value);
}
var updatePlayers = (from p in _dbContext.manchesterUnitedTeams
where p.ID == barID
select p).SingleOrDefault();
if (updatePlayers != null)
{
updatePlayers.LastName = mLastNameTextBox.Text;
updatePlayers.FirstName = mFirstNameTextBox.Text;
updatePlayers.Phone = mCellNumberTextBox.Text;
updatePlayers.PlayersPosition = mPositionComboBox.Text;
}
try
{
//Submit to datagridview
_dbContext.SubmitChanges();
//Refresh datagridview
team2DataGridView.RefreshEdit();
}
catch (Exception exception)
{
//Show an error message
MessageBox.Show(exception.Message);
}
}
I think your dbContext.Submit method is just not actually submitting the value of the data members of 2 tab . Its just sending the values of your team 1 variables once again
I am creating an application with an XML file called star.xml to store my data in a list view. I am very new to c# and programming and need any help
Basically, I want to be able to type in my search text box (called 'search') and for my list view (lstStar) to only show the matching records. I.e. typing in 'Audi' will only return those items.
any help will be much appreciated
jen
namespace StarinCar
{
public partial class MainWindow : Window
{
int hot = -2;
int Mildly_Moist = -2;
int Wet = -4;
int Very_Wet = -6;
private ObservableCollection<star> starData;
public MainWindow()
{
InitializeComponent();
starData = new ObservableCollection<star>();
lstStar.ItemsSource = starData;
try
{
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<star>));
using (StreamReader rd = new StreamReader("star.xml"))
{
starData = xs.Deserialize(rd) as ObservableCollection<star>;
}
}
catch
{
}
lstStar.ItemsSource = starData;
lblAverage.Content = starData.Average(i => i.time).ToString();
lblFastest.Content = starData.Min(i => i.time).ToString();
lblSlowest.Content = starData.Max(i => i.time).ToString();
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
star newStar = new star();
newStar.firstName = txtName.Text;
newStar.time = int.Parse(txtTime.Text);
newStar.car = txtCar.Text;
newStar.track = txtTrack.Text;
starData.Add(newStar);
if (txtTrack.Text.Contains("Hot") || (txtTrack.Text.Contains("hot") == true))
{
newStar.time = int.Parse(txtTime.Text) + hot;
}
if (txtTrack.Text.Contains("Mildly Moist") || (txtTrack.Text.Contains("mildly moist")) == true)
{
newStar.time = int.Parse(txtTime.Text) + Mildly_Moist;
}
if (txtTrack.Text.Contains("Wet") || (txtTrack.Text.Contains("wet") == true))
{
newStar.time = int.Parse(txtTime.Text) + Wet;
}
if (txtTrack.Text.Contains("Very Wet") || (txtTrack.Text.Contains("very wet")) == true)
{
newStar.time = int.Parse(txtTime.Text) + Very_Wet;
}
}
private void Window_Closed(object sender, EventArgs e)
{
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<star>));
using (StreamWriter wr = new StreamWriter("star.xml"))
{
xs.Serialize(wr, starData);
}
}
}
}
You could use ICollectionView. So you would have your "overall"
star collection 'starData'. But your listbox itemssource would be bound to something like this:
public ICollectionView FilteredStars
{
get
{
ICollectionView source = CollectionViewSource.GetDefaultView(starData);
source.Filter = new Predicate<object>(FilterStars);
return source;
}
}
the logic that does the filtering here:
private bool FilterStars(object item)
{
bool b = false;
star a = item as star;
if (a != null)
{
if (a.Name.Contains(searchBoxText)) //your filter logic here
{
b = true;
}
else if String.IsNullOrWhiteSpace(searchBoxText)
{
b = true;
}
}
return b;
}
Basically, you have your main collection, then some logic that filters your main collection to a filtered collection, and that's what you should set itemssource of your listbox to. This, so far, is assuming you are going to put some kind of property change into your search text box and probably then click a button, like "Search" to then tell the list to check and re-populate to match the search term.
This is how I filter in a similar application
public IEnumerable<string> PastEntries1
{
get
{
if(string.IsNullOrEmpty(textValue))
{
return FieldDefString.PastEntries;
}
else
{
return FieldDefString.PastEntries.Where(x => x.StartsWith(textValue, StringComparison.OrdinalIgnoreCase));
}
}
}
I have checkboxes in my asp.net gridview and I have a method to select multiple checkboxes and that works great. After that when the user inputs a value in the textbox to be updated to the rows selected the values I just set are null again? I have included my method of checking multiple items and my update button. Why are the values not being retained and how can I fix it?
public variables
public string values = "";
public string salesorderNumber;
Multiple checkboxes
protected void SelectCheckBox_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chk = sender as CheckBox;
var rows = dropdeadGridView.Rows;
int count = dropdeadGridView.Rows.Count;
for (int i = 0; i < count; i++)
{
bool isChecked = ((CheckBox)rows[i].FindControl("SelectCheckBox")).Checked;
if (isChecked)
{
values += rows[i].Cells[1].Text + ",";
rows[i].BorderColor = System.Drawing.Color.Red;
rows[i].ForeColor = System.Drawing.Color.Red;
rows[i].BorderStyle = BorderStyle.Inset;
}
}
}
Update Button
protected void UpdateButton_Click(object sender, EventArgs e)
{
App_Code.GridData gridData = new App_Code.GridData();
if (loadnumTextBox.Text == "" && RadDateTimePicker1.SelectedDate != null)
{
SqlConnection dbConn = App_Code.DBHelper.getConnection();
try
{
using (dbConn)
{
SqlCommand addJob = new SqlCommand(#"UPDATE ORDER_DETAIL SET DropDeadTime = #DropDeadTime WHERE SALES_ORDER_NUMBER = #SalesOrderNumber", dbConn);
//addJob.Parameters.AddWithValue("#SalesOrderNumber", Convert.ToInt32(IDTextBox.Text));
addJob.Parameters.AddWithValue("#SalesOrderNumber", values);
addJob.Parameters.AddWithValue("#DropDeadTime", RadDateTimePicker1.SelectedDate);
dbConn.Open();
addJob.ExecuteNonQuery();
}
NotificationLabel.Text = "Updated!";
NotificationLabel.Visible = true;
}
catch (Exception ex)
{
throw ex;
}
BindList();
}
if (loadnumTextBox.Text != "" && RadDateTimePicker1.SelectedDate == null)
{
SqlConnection dbConn = App_Code.DBHelper.getConnection();
try
{
using (dbConn)
{
SqlCommand addJob = new SqlCommand(#"UPDATE ORDER_DETAIL SET LOAD_NUMBER = #LOAD_NUMBER WHERE SALES_ORDER_NUMBER = #SalesOrderNumber", dbConn);
addJob.Parameters.AddWithValue("#SalesOrderNumber", salesorderNumber);
addJob.Parameters.AddWithValue("#LOAD_NUMBER", loadnumTextBox.Text);
dbConn.Open();
addJob.ExecuteNonQuery();
}
NotificationLabel.Text = "Updated!";
NotificationLabel.Visible = true;
}
catch (Exception ex)
{
throw ex;
}
BindList();
}
If you want it to live between requests you'll have to use something like session-state, view-state, a cookie, or a HTML form / request value.
ASP.NET is stateless meaning it does not keep it state from post back to postback.
You need a static one if you want to achieve your goal.
i am using telerik control(data grid view) in my project. but when i want to add new row in data grid, the text of previous rows (bindingSourceService.DataSource = dtservice , bindingSourceUnit.DataSource = dtunit) disappear.
my datagridview has 3 combobox column.
what is wrong? please help me.
my codes:
public void FactorLoad(object sender, EventArgs e)
{
try
{
var cb = new CategoriBll();
DataTable dtcategori = cb.GetAllDataCategori();
bindingSourceCategouri.DataSource = dtcategori;
}
catch (Exception ex)
{
ExceptionkeeperBll.LogFileWrite(ex);
}
}
private void DataGridViewFactorCellValueChanged(object sender, GridViewCellEventArgs e)
{
try
{
var row = DataGridViewFactor.CurrentRow;
if ((row != null) && (row.Cells[0].IsCurrent))
{
var categoryId = Convert.ToInt32(DataGridViewFactor.CurrentRow.Cells[0].Value);
var sb = new CategoriOptionBll();
DataTable dtservice = sb.ServiceGetById(categoryId);
bindingSourceService.DataSource = dtservice;
}
if ((row != null) && (row.Cells[1].IsCurrent))
{
var serviceId = Convert.ToInt32(DataGridViewFactor.CurrentRow.Cells[1].Value);
var cbi = new CostBll();
var dtunit = cbi.CostById(serviceId);
bindingSourceUnit.DataSource = dtunit;
}
}
catch (Exception ex)
{
ExceptionkeeperBll.LogFileWrite(ex);
}
}
private void DataGridViewFactorCellEditorInitialized(object sender, GridViewCellEventArgs e)
{
try
{
var row = DataGridViewFactor.CurrentRow;
if ((row != null) && (row.Cells[0].IsCurrent))
{
var categoryId = Convert.ToInt32(DataGridViewFactor.CurrentRow.Cells[0].Value);
var sb = new CategoriOptionBll();
DataTable dtservice = sb.ServiceGetById(categoryId);
bindingSourceService.DataSource = dtservice;
}
if ((row != null) && (row.Cells[1].IsCurrent))
{
var serviceId = Convert.ToInt32(DataGridViewFactor.CurrentRow.Cells[1].Value);
var cbi = new CostBll();
var dtunit = cbi.CostById(serviceId);
bindingSourceUnit.DataSource = dtunit;
}
}
catch (Exception ex)
{
ExceptionkeeperBll.LogFileWrite(ex);
}
}
It will disappear because there will be only 1 value in the data source. Try adding value to the data source rather then assigning single value.
Im having problems with this simple function on a textbox.. I have a winforms application, with a textbox, set up to autocomplete like this:
if (rbSerialNumSearch.Checked)
{
txtSerialNum.Enabled = true;
AutoCompleteStringCollection data = new AutoCompleteStringCollection();
//Test data
data.Add("555-777-333");
data.Add("222-333-444");
data.Add("111-222-333");
txtSerialNum.AutoCompleteCustomSource = data;
txtSerialNum.AutoCompleteMode = AutoCompleteMode.Suggest;
txtSerialNum.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
But it is not working. Nothing appears when i type in the textbox? If i i specify strings directly to the textbox collection property (in design mode), it works fine, but when i try to add strings programmatically, nothing happends?
Thanks in advance..
ENTIRE CODE FOR FORM HERE:
namespace GUI
{
public partial class UpdateEquipmentForm : Form
{
EquipmentManager em;
ProductManager pm;
CategoryManager cm;
public UpdateEquipmentForm()
{
InitializeComponent();
em = new EquipmentManager();
pm = new ProductManager();
cm = new CategoryManager();
}
private void btnSearch_Click(object sender, EventArgs e)
{
if (rbCategorySearch.Checked)
{
List<Equipment> equipments = em.GetAllEquipmentInStock().Where(eq => eq.Product.Category_Id == (int)cbChooseCategory.SelectedValue).ToList();
var resultset = (from eq in equipments
select new { eq.Product.ProductNameNum, eq.Id, eq.SerialNumber, eq.InvoiceNumber, eq.CreatedDate, eq.ExpiryDate, eq.FirstUseDate }).ToList();
dgvResult.DataSource = resultset;
}
if (rbProductsSearch.Checked)
{
List<Equipment> equipments = em.GetAllEquipmentInStock().Where(eq => eq.Product.Id == (int)cbChooseType.SelectedValue).ToList();
var resultset = (from eq in equipments
select new { eq.Product.ProductNameNum, eq.Id, eq.SerialNumber, eq.InvoiceNumber, eq.CreatedDate, eq.ExpiryDate, eq.FirstUseDate }).ToList();
dgvResult.DataSource = resultset;
}
if (rbSerialNumSearch.Checked)
{
List<Equipment> equipments = em.GetAllEquipmentInStock();
var resultset = (from eq in equipments
where eq.SerialNumber.Contains(txtSearchEquipment.Text)
select new { eq.Product.ProductNameNum, eq.Id, eq.SerialNumber, eq.InvoiceNumber, eq.CreatedDate, eq.ExpiryDate, eq.FirstUseDate }).ToList();
dgvResult.DataSource = resultset;
}
}
private void rbCategorySearch_CheckedChanged(object sender, EventArgs e)
{
if (rbCategorySearch.Checked)
{
cbChooseCategory.Enabled = true;
cbChooseCategory.DataSource = cm.GetAllActiveCategories();
cbChooseCategory.DisplayMember = "Name";
cbChooseCategory.ValueMember = "Id";
}
else
{
cbChooseCategory.Enabled = false;
}
}
private void rbProductsSearch_CheckedChanged(object sender, EventArgs e)
{
if (rbProductsSearch.Checked)
{
cbChooseType.Enabled = true;
cbChooseType.DataSource = pm.GetAllActiveProducts();
cbChooseType.DisplayMember = "ProductNameNum";
cbChooseType.ValueMember = "Id";
}
else
{
cbChooseType.Enabled = false;
}
}
private void rbSerialNumSearch_CheckedChanged(object sender, EventArgs e)
{
if (rbSerialNumSearch.Checked)
{
txtSerialNum.Enabled = true;
AutoCompleteStringCollection data = new AutoCompleteStringCollection();
data.Add("555-777-333");
data.Add("222-333-444");
data.Add("111-222-333");
txtSerialNum.AutoCompleteCustomSource = data;
txtSerialNum.AutoCompleteMode = AutoCompleteMode.Suggest;
txtSerialNum.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
else
{
txtSerialNum.Enabled = false;
}
}
}
}
Found the problem.. Really stupid of me. I was referencing the wrong textbox :-( The one i should be referencing is called txtSearchSerial and not txtSerialNum. Doh !
Appreciate the effort guys..thanks.
You can set a break point to
txtSerialNum.Enabled = true;
I think this application never run into this block.
Or after this code, you re-set the binding of txtSerialNum.