C# DataGridView ImageColumn - c#

DataGridView Image Column is getting null when change the visibility of User Control that includes the dataGridView. Codes are below;
public partial class ReadingOrderListControl : UserControl
{
private Image Pending { get { return Image.FromFile(#"..\..\Resources\pending.png"); } }
private Image Completed { get { return Image.FromFile(#"..\..\Resources\completed.png"); } }
private void ReadingOrderListControl_Load(object sender, EventArgs e)
{
GetOrderList();
}
private void GetOrderList()
{
dgv_ReadingOrders.DataSource = DbManager.GetReadingOrders();
if (dgv_ReadingOrders.Rows[0].Cells["tamamlanma"].Value.ToString() == "1")
dgv_ReadingOrders.Rows[0].Cells["tamamlanma_image"].Value = Completed;
else
dgv_ReadingOrders.Rows[0].Cells["tamamlanma_image"].Value = Pending;
}
}

Try this:
if (dgv_ReadingOrders.Rows[0].Cells["tamamlanma"].Value.ToString() == "1")
dgv_ReadingOrders.Rows.Add(ID,...... , Bitmap.FromFile(Completed));
else
dgv_ReadingOrders.Rows.Add(ID,...... , Bitmap.FromFile(Pending));

Related

The data I enter into a TextBox is not being assigned to the value variable in a UWP app

I'm working on a simple UWP app, using Template 10. I want to enter monetary data into a TextBox. It's my understanding that I should use a string variable in the View-Model. So, for the moment I'm just making sure that the data I enter, when running the app, actually works. But it doesn't. When running or debugging it, and if I enter something like "10" (without the double quotes), what the variable value is assigned is "0". Which doesn't make sense to me. Here's the XAML:
<TextBox
x:Name="HourlyTextBox"
Style="{StaticResource CommonTextboxStyle}"
Text="{x:Bind ViewModel.Hourly, Mode=TwoWay}" />
And here's the code from the View-Model:
private string hourly;
public string Hourly
{
get => hourly;
set
{
_ = Set(ref hourly, value);
}
}
Here's the Code-behind code:
using Windows.UI.Xaml.Controls;
using SalaryConv;
namespace SalaryConversion.Views
{
public sealed partial class MainPage : Page
{
private SalaryUnitsEnum lastHadFocus;
public MainPage()
{
InitializeComponent();
NavigationCacheMode =
Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
}
#region GettingFocus events
private void HourlyTextBox_GettingFocus(Windows.UI.Xaml.UIElement sender, Windows.UI.Xaml.Input.GettingFocusEventArgs args)
{
if (lastHadFocus == SalaryUnitsEnum.Hourly)
{
return;
}
lastHadFocus = SalaryUnitsEnum.Hourly;
ClearOtherMonetaryTextboxes(lastHadFocus);
}
private void WeeklyTextBox_GettingFocus(Windows.UI.Xaml.UIElement sender, Windows.UI.Xaml.Input.GettingFocusEventArgs args)
{
if (lastHadFocus == SalaryUnitsEnum.Weekly)
{
return;
}
lastHadFocus = SalaryUnitsEnum.Weekly;
ClearOtherMonetaryTextboxes(lastHadFocus);
}
private void BiWeeklyTextBox_GettingFocus(Windows.UI.Xaml.UIElement sender, Windows.UI.Xaml.Input.GettingFocusEventArgs args)
{
if (lastHadFocus == SalaryUnitsEnum.BiWeekly)
{
return;
}
lastHadFocus = SalaryUnitsEnum.BiWeekly;
ClearOtherMonetaryTextboxes(lastHadFocus);
}
private void SemiMonthlyTextBox_GettingFocus(Windows.UI.Xaml.UIElement sender, Windows.UI.Xaml.Input.GettingFocusEventArgs args)
{
if (lastHadFocus == SalaryUnitsEnum.SemiMonthly)
{
return;
}
lastHadFocus = SalaryUnitsEnum.SemiMonthly;
ClearOtherMonetaryTextboxes(lastHadFocus);
}
private void MonthlyTextBox_GettingFocus(Windows.UI.Xaml.UIElement sender, Windows.UI.Xaml.Input.GettingFocusEventArgs args)
{
if (lastHadFocus == SalaryUnitsEnum.Monthly)
{
return;
}
lastHadFocus = SalaryUnitsEnum.Monthly;
ClearOtherMonetaryTextboxes(lastHadFocus);
}
private void AnnuallyTextBox_GettingFocus(Windows.UI.Xaml.UIElement sender, Windows.UI.Xaml.Input.GettingFocusEventArgs args)
{
if (lastHadFocus == SalaryUnitsEnum.Annually)
{
return;
}
lastHadFocus = SalaryUnitsEnum.Annually;
ClearOtherMonetaryTextboxes(lastHadFocus);
}
#endregion
#region ClearOtherMonetaryTextboxes helper method
private void ClearOtherMonetaryTextboxes(SalaryUnitsEnum lastHadFocus)
{
if (lastHadFocus != SalaryUnitsEnum.Hourly)
{
HourlyTextBox.Text = "0";
}
if (lastHadFocus != SalaryUnitsEnum.Weekly)
{
WeeklyTextBox.Text = "0";
}
if (lastHadFocus != SalaryUnitsEnum.BiWeekly)
{
BiWeeklyTextBox.Text = "0";
}
if (lastHadFocus != SalaryUnitsEnum.SemiMonthly)
{
SemiMonthlyTextBox.Text = "0";
}
if (lastHadFocus != SalaryUnitsEnum.Monthly)
{
MonthlyTextBox.Text = "0";
}
if (lastHadFocus != SalaryUnitsEnum.Annually)
{
AnnuallyTextBox.Text = "0";
}
}
#endregion
}
}
Thanks to Richard Zhang's suggestion of looking at my code-behind, I discovered there that I had previously written some code to handle the controls on the screen. It was this code which was resetting the values to 0 (indirectly). I had written that code a while ago, so I'd forgotten all about it.
Thank you, Richard, for making that suggestion. It helped me see what I had done and after reviewing it I was able to easily resolve it.

Variables getting reinitialised when clicking on Button in C#

I am making an online form. I initialise 4 variables in my code at the beginning. When I select a dropdown, an event (DropDownList4_SelectedIndexChanged ) gets fired which in turn call Availability(). Here my boolean variable avail_bus is assigned a value. However, when i click on submit button ( Button1_Click1), the variable avail_bus is reinitialised to false. I debugged this and found out that upon clicking on Submit(Button1_Click1) the control first goes to the top of the code in the page which is
public partial class Appform : System.Web.UI.Page
{
private bool isNotDup = true;
private bool avail_bus ;
private int max_capacity_bus;
private int realAvailability;
}
and then goes to Button1_click1 .
How can I prevent this from happening ? If the state of avail_bus is changed to true while calling availability, it should not get reinitialized to true when i click on submit.
Below is my code :
namespace eTransport
{
public partial class Appform : System.Web.UI.Page
{
private bool isNotDup = true;
private bool avail_bus ;
private int max_capacity_bus;
private int realAvailability;
protected void Page_Load (object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindDropDown();
}
}
//Method called when dropdown is selected in Bus Stop. It helps to populate Bus Number
protected void DropDownList4_SelectedIndexChanged (object sender, EventArgs e)
{
AutoPopulateBusStop();
Availability();
}
//Method to load drop down values in Bus Stop. These are populated from database
protected void BindDropDown ()
{
//some code here
}
//Method to autopopulate Bus Number based on selection of Bus Stop. The mapping is in the database in the table named -> dropdownlist
protected void AutoPopulateBusStop ()
{
//some code here
}
protected void Availability ()
{
string constr5 = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (SqlConnection con5 = new SqlConnection(constr5))
{
try
{
using (SqlCommand cmd5 = new SqlCommand("select count(*) from etms where BusNo='" + TextBox6.Text.ToString() + "'"))
{
cmd5.CommandType = CommandType.Text;
cmd5.Connection = con5;
con5.Open();
int capacity_from_db = Convert.ToInt16(cmd5.ExecuteScalar());
realAvailability = max_capacity_bus - capacity_from_db;
if (realAvailability > 0)
{
avail_bus = true;
TextBox2.Text = realAvailability.ToString() + " seats available ";
TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#008000");
}
else
{
TextBox2.Text = "Seats Not available. Please choose another Stop";
TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff1919");
}
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}
}
protected void Button1_Click1 (object sender, EventArgs e)
{
if (isNotDup)
{
if (avail_bus)
{
// Submit the Form
}
else
{
Label14.Text = "Bus Seats not available!";
Label15.Text = null;
}
}
}
protected void PhoneNumberValidatation (object source, ServerValidateEventArgs args)
{
//some code here
}
}
}
There are three possible solution for this question.
Static - This will create one instance that accessible to all pages (Global).
private static avail_bus = true;
Session State - This enables you to store and retrieve values for a user as the user navigates.
// Get...
private bool avail_bus = (bool)Session["avail_bus"];
// Set
Session["avail_bus"] = true;
Control.ViewState - Gets a dictionary of state information that allows you to save and restore the view state of a server control across multiple requests for the same page.
public bool avail_bus
{
get { return ViewState["avail_bus"] == null ? false : (bool)ViewState["avail_bus"]; }
set { ViewState["avail_bus"] = value; }
}
Every time there is a request for your page, a new instance of that page-class is created to handle that request. So any fields are re-initialized.
You can store a value in ViewState to remember a value over various requests:
namespace eTransport
{
public partial class Appform : System.Web.UI.Page
{
private bool isNotDup
{
set { ViewState["isNotDup "] = value; }
get
{
if (ViewState["isNotDup "] == null)
return true;
return (bool )ViewState["isNotDup "];
}
}
private bool avail_bus
{
set { ViewState["avail_bus"] = value; }
get
{
if (ViewState["avail_bus"] == null)
return true;
return (bool )ViewState["avail_bus"];
}
}
private int max_capacity_bus
{
set { ViewState["max_capacity_bus "] = value; }
get
{
if (ViewState["max_capacity_bus "] == null)
return 0;
return (int)ViewState["max_capacity_bus "];
}
}
private int realAvailability
{
set { ViewState["realAvailability"] = value; }
get
{
if (ViewState["realAvailability"] == null)
return 0;
return (int)ViewState["realAvailability"];
}
}
protected void Page_Load (object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindDropDown();
}
}
//Method called when dropdown is selected in Bus Stop. It helps to populate Bus Number
protected void DropDownList4_SelectedIndexChanged (object sender, EventArgs e)
{
AutoPopulateBusStop();
Availability();
}
//Method to load drop down values in Bus Stop. These are populated from database
protected void BindDropDown ()
{
//some code here
}
//Method to autopopulate Bus Number based on selection of Bus Stop. The mapping is in the database in the table named -> dropdownlist
protected void AutoPopulateBusStop ()
{
//some code here
}
protected void Availability ()
{
string constr5 = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (SqlConnection con5 = new SqlConnection(constr5))
{
try
{
using (SqlCommand cmd5 = new SqlCommand("select count(*) from etms where BusNo='" + TextBox6.Text.ToString() + "'"))
{
cmd5.CommandType = CommandType.Text;
cmd5.Connection = con5;
con5.Open();
int capacity_from_db = Convert.ToInt16(cmd5.ExecuteScalar());
realAvailability = max_capacity_bus - capacity_from_db;
if (realAvailability > 0)
{
avail_bus = true;
TextBox2.Text = realAvailability.ToString() + " seats available ";
TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#008000");
}
else
{
TextBox2.Text = "Seats Not available. Please choose another Stop";
TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff1919");
}
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}
}
protected void Button1_Click1 (object sender, EventArgs e)
{
if (isNotDup)
{
if (avail_bus)
{
// Submit the Form
}
else
{
Label14.Text = "Bus Seats not available!";
Label15.Text = null;
}
}
}
protected void PhoneNumberValidatation (object source, ServerValidateEventArgs args)
{
//some code here
}
}
}
You can store the availability status in a hidden input field which later gets posted on Button1 click event.
And in button1 click event instead of accessing the avail value from variable access it from hiddenField's value
Another option would be calling Availability() again in click event of button1 as a first line so that it sets proper value in the avail_bus variable

nested unit of work and making unwanted object

I have 3 forms in my application : frmTrucks, frmEditTruck and frmEditContent.
frmTrucks shows my Trucks in a grid.
I add a truck, or choose one of the trucks from the grid to edit in frmEditTruck
public void Edit()
{
using (NestedUnitOfWork nuow = session.BeginNestedUnitOfWork())
{
Truck currentTruck = nuow.GetNestedObject(
xpcTruck[gvTruck.GetDataSourceRowIndex(gvTruck.FocusedRowHandle)])
as Truck;
using (frmEditTruck form = new frmEditTruck(currentTruck))
{
if (form.ShowDialog() == DialogResult.OK)
nuow.CommitChanges();
}
}
}
in frmEditTruck there are some text boxes for truck properties and two buttons.
btnSave and btnAddContent. btnSave saves the changes (now.CommitChanges();). btnAddContent's click code is :
Truck truck;
Session session;
public frmEditTruck(Truck truck)
{
InitializeComponent();
this.truck = truck;
this.session = truck.Session;
}
private void btnAddContent_Click(object sender, EventArgs e)
{
TContent content = new TContent(session);
using (frmEditTContent form = new frmEditTContent(content, truck))
{
if (form.ShowDialog() == DialogResult.OK)
truck.TContents.Add(content);
}
}
it shows frmEditContent. I can Add content to my truck. the problem is when I press AddContent and then cancel it. After that when I press the save button on my frmEditTruck it would add an empty row to my Content Table. I want to fix this problem. how can I fix it? I'm not sure my problem is clear enough for you. Please let me know
public class Truck : XPObject
{
.
.
.
[Association("Truck-TContents")]
public XPCollection<TContent> TContents { get { return GetCollection<TContent>("TContents"); } }
}
public class TContent : XPObject
{
.
.
.
private Truck truck;
[Association("Truck-TContents")]
public Truck Truck
{
get
{
return truck;
}
set
{
SetPropertyValue("Truck", ref truck, value);
}
}
}
private void btnAddContent_Click(object sender, EventArgs e)
{
TContent content = new TContent(session);
using (frmEditTContent form = new frmEditTContent(content, truck))
{
if (form.ShowDialog() == DialogResult.OK)
truck.TContents.Add(content);
}
}
I've changed the code to:
private void btnAddContent_Add(object sender, EventArgs e)
{
TContent content = new TContent(session);
using (frmEditTContent form = new frmEditTContent(content, truck))
{
if (form.ShowDialog() == DialogResult.OK)
{
truck.TContents.Add(content);
}
else
{
if (session.TrackingChanges)
session.RollbackTransaction();
}
}
}
and it works properly.

Combobox SelectedItem property return always and show always the first item

I have 3 combobox ObjetivosCB, FrecuenciasCB and ResponsablesCB in my form as shows below
public partial class Form_Indicador : Form
{
public Indicador Indicador { get; set; }
private void Form_AgregarIndicador_Load(object sender, EventArgs e)
{
if (Indicador == null)
Indicador = new Indicador();
ConfigurarObjetivosCB();
ConfigurarFrecuenciasCB();
ConfigurarResponsablesCB();
CargarPropiedadesIndicador();
}
private void ConfigurarResponsablesCB()
{
ResponsableCB.DataSource = ResponsableRepository.Instance.All();
ResponsableCB.DisplayMember = "Area";
if (Indicador.Responsable == null)
ResponsableCB.SelectedIndex = -1;
}
private void ConfigurarFrecuenciasCB()
{
FrecuenciasCB.DisplayMember = "Periodo";
FrecuenciasCB.DataSource = IndicadorRepository.Instance.AllFrecuencias();
if (Indicador.Frecuencia == null)
FrecuenciasCB.SelectedIndex = -1;
}
private void ConfigurarObjetivosCB()
{
ObjetivosCB.DataSource = _objetivoFachada.All();
ObjetivosCB.DisplayMember = "Nombre";
if (Indicador.Objetivo == null) ObjetivosCB.SelectedIndex = -1;
}
private void CargarPropiedadesIndicador()
{
ObjetivosCB.DataBindings.Add("SelectedItem", Indicador, "Objetivo");
ResponsableCB.DataBindings.Add("SelectedItem", Indicador, "Responsable");
FrecuenciasCB.DataBindings.Add("SelectedItem", Indicador, "Frecuencia");
}
}
The problem is that FrecuenciasCB.SelectedItem and ResponsablesCB.SelectedItem always show and return the first item but ObjetivosCB.SelectedItem works fine. I am not understand... three methods has the same logic. What am I doing wrong?
I have been solved! The problem was a wrong definition for Equals() in Indicador and Frecuencia.

Datagrid not populating past headers

Thanks in advance for any help. I've been working with the tutorial listed here, but have run into an issue. I'm attempting to populate a datagrid in silverlight, but when I submit the button click, it will return the headers for columns but no data. I know data is in the system, so I'm confused why it's going to get the headers but not the actual data to populate. Code from my MainPage.xaml.cs and my data domain are below.
MainPage.xaml.cs
namespace SandCherryDemo
{
public partial class MainPage : UserControl
{
private SandCherryViewContext _sandCherryContext = new SandCherryViewContext();
public MainPage()
{
InitializeComponent();
}
private void StatusButton_Click(object sender, RoutedEventArgs e)
{
StatusButton.IsEnabled = false;
LoadOperation<SandCherryView> loadOp = this._sandCherryContext.Load(this._sandCherryContext.GetEQPByStatusQuery(StatusValue.Text), DataLoadedCallback, null);
SandCherryGrid.ItemsSource = loadOp.Entities;
}
void DataLoadedCallback(LoadOperation<SandCherryView> loadOperation)
{
StatusButton.IsEnabled = true;
}
}
}
SandCherryViewService.cs
[EnableClientAccess()]
public class SandCherryViewService : LinqToEntitiesDomainService<Charter_SandCherryEntities>
{
[Query(IsComposable=false)]
public IQueryable<SandCherryView> GetEQPByStatus(string status)
{
return this.ObjectContext.SandCherryViews.Where(e => e.StatusDescr.StartsWith(status) == true);
}
// TODO:
// Consider constraining the results of your query method. If you need additional input you can
// add parameters to this method or create additional query methods with different names.
// To support paging you will need to add ordering to the 'SandCherryViews' query.
public IQueryable<SandCherryView> GetSandCherryViews()
{
return this.ObjectContext.SandCherryViews;
}
public void InsertSandCherryView(SandCherryView sandCherryView)
{
if ((sandCherryView.EntityState != EntityState.Detached))
{
this.ObjectContext.ObjectStateManager.ChangeObjectState(sandCherryView, EntityState.Added);
}
else
{
this.ObjectContext.SandCherryViews.AddObject(sandCherryView);
}
}
public void UpdateSandCherryView(SandCherryView currentSandCherryView)
{
this.ObjectContext.SandCherryViews.AttachAsModified(currentSandCherryView, this.ChangeSet.GetOriginal(currentSandCherryView));
}
public void DeleteSandCherryView(SandCherryView sandCherryView)
{
if ((sandCherryView.EntityState != EntityState.Detached))
{
this.ObjectContext.ObjectStateManager.ChangeObjectState(sandCherryView, EntityState.Deleted);
}
else
{
this.ObjectContext.SandCherryViews.Attach(sandCherryView);
this.ObjectContext.SandCherryViews.DeleteObject(sandCherryView);
}
}
}
}
Since your data is not loaded yet. Try setting the ItemsSource of your grid in DataLoadedCallBack event -
void DataLoadedCallback(LoadOperation<SandCherryView> loadOperation)
{
StatusButton.IsEnabled = true;
SandCherryGrid.ItemsSource = loadOp.Entities;
}

Categories