GridView DataBinding - c#

I have a problem with a GridView(I'm using Telerick but i think the .NET GridView is similar for this situation).
I have a List that contains some user define object with some properties that will be displayed in a GridView. This list is loaded from SQL.
My problem is that i have an int property that i want to be parsed and displayed in GridView with some strings.
public class Vehicles
{
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string vehName;
public string VehName
{
get { return vehName; }
set { vehName = value; }
}
private int gpsInterval;
public int GpsInterval
{
get { return gpsInterval; }
set { gpsInterval = value; }
}
private int isStolen;
public int IsStolen
{
get { return isStolen; }
set { isStolen = value; }
}
...
}
...
List<Vehicles> vehs = DBveh.getAllVehicles();
GridViewUnitsList.DataSource = vehs;
Is stolen is curently displayed as an int in the GridView. So is there a method to parse "isStolen" value and replace it with somenting like "YES"/"NO" without using a foreach and iterating throw the hole GridView after the binding?

There are 2 easy options:
1) Add a property to your object and reference that property in the DataGrid:
public string IsStolenStr
{
get { return isStolen == 1? "Yes" : "No"; }
}
2) Or add the logic to a <asp:template> column in the DataGrid:
<%# Eval("IsStolen") == 1 ? "Yes" : "No" %>

I would modify the SQL statement so that it returned the Yes/No string based on the isStolen value.

Related

Change the xtragrid detailsView type programmatically devepxress

I have this code
private string _nom;
private string _reference;
private BindingList<Contact> _listContact = null;
public string Nom
{
get { return _nom; }
set { _nom = value; }
}
public string Reference
{
get { return _reference; }
set { _reference = value; }
}
public BindingList<Contact> ListContact
{
get { return _listContact; }
set { _listContact = value; }
}
And Ihave a function that return BindingList
In my XtraForm I have this
listPartenaire = Partenaires.getPartenairesObjectUsingLinq();
dgv.DataSource = listPartenaire;
Well with that, I have an xtraGrid filled by Partenaire in the MasterView, and with the Contact in the DetailsView
What I'm looking for is to change the type of the detailsview to CardView or something else with c#
any help please
I believe the following help article should be helpful: Specify Views to Represent Detail Data
Please check the example:
How to: Replace a View Used to Represent a Specific Master-Detail Relationship

populating datagridview with list of objects

I have a List that contains a series of transaction objects. What I'm trying to do is to display these transaction objects in a Datagridview control on loading a form, basically the Datagridview should represent something of a transaction register to display the data for each of the transaction objects in the list.
I must admit to a lack of experience when it comes to using Datagridviews and I'm having some difficulty with understanding what I need to do here.
My question is, how do I go about getting the details of each of the objects in the list to display in the Datagridview?
Here is my code.
First the transaction class:
public class Transaction
{
// Class properties
private decimal amount;
private string type;
private decimal balance;
private string date;
private string transNum;
private string description;
// Constructor to create transaction object with values set.
public Transaction(decimal amount, string type, decimal currBal, string date, string num, string descrip)
{
this.amount = amount;
this.type = type;
this.balance = currBal;
this.date = date;
this.transNum = num;
this.description = descrip;
}
// Get and Set accessors to allow manipulation of values.
public decimal Amount
{
get
{
return amount;
}
set
{
amount = value;
}
}
public string Type
{
get
{
return type;
}
set
{
type = value;
}
}
public decimal Balance
{
get
{
return balance;
}
set
{
balance = value;
}
}
public string Date
{
get
{
return date;
}
set
{
date = value;
}
}
public string TransNum
{
get
{
return transNum;
}
set
{
transNum = value;
}
}
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public decimal addCredit(decimal balance, decimal credit)
{
decimal newBalance;
newBalance = balance + credit;
return newBalance;
}
public decimal subtractDebit(decimal balance, decimal debit)
{
decimal newBalance;
newBalance = balance - debit;
return newBalance;
}
}
}
Now the code for the "Register" form:
public partial class Register : Form
{
List<Transaction> tranList = new List<Transaction>();
public Register(List<Transaction> List)
{
InitializeComponent();
this.tranList = List;
}
private void Register_Load(object sender, System.EventArgs e)
{
//regView represents the Datagridview that I'm trying to work with
regView.AutoSize = true;
regView.DataSource = tranList;
regView.Rows.Add(tranList[0]);
}
}
And here's the output I get.
There's really two high level approaches to this.
1) Add the manually created rows directly to the DataGridView. In this case, you have to manually update/remove them as things change. This approach is "ok" if you don't intend to alter/change the content of the display after you initialize it. It becomes untenable if you do.
To add it directly, you need to create a DataGridViewRow, and populate it with the individual values, and then add the DataGridViewRow to the DataGridView.Rows.
2) Data bind the DGV. There's many articles about databinding to a DataGridView. In some cases, it's easier to just add your data to a DataTable, and then extract a DataView from that, and bind the DataGridView to the DataView. Other people find it easier to directly bind to a collection.
CodeProject has a decent article to get you started down that path, but a quick Google search will yield many other articles.
http://www.codeproject.com/Articles/24656/A-Detailed-Data-Binding-Tutorial
use as DGV:
DataGridView groupListDataGridView;
column:
DataGridViewTextBoxColumn groupListNameColumn;
column setup should be like this:
groupListNameColumn.DataPropertyName = "name";
use this property, else all columns will be added.
groupListDataGridView.AutoGenerateColumns = false;
populate like this:
private void populateGroupList() {
groupListDataGridView.DataSource = null;
formattedGroupList = new SortableBindingList<DataGridGroupObject>();
foreach (GroupObject go in StartUp.GroupList) {
DataGridGroupObject dggo = new DataGridGroupObject();
dggo.id = go.Id;
dggo.name = go.Name;
formattedGroupList.Add(dggo);
}
groupListDataGridView.DataSource = formattedGroupList;
groupListDataGridView.Invalidate();
}
and model:
public class DataGridGroupObject
{
public int id { get; set; } //this will be match id column
public string name { get; set; } // this will be match name column
}
Simply add using System.Linq; at the top. Then you can do this:
//This will create a custom datasource for the DataGridView.
var transactionsDataSource = tranList.Select(x => new
{
Amount = x.amount,
Type = x.type,
Balance = x.balance,
Date = x.date,
TransNum = x.transNum
Description = x.description
}).ToList();
//This will assign the datasource. All the columns you listed will show up, and every row
//of data in the list will populate into the DataGridView.
regView.DataSource = transactionsDataSource;

How do I reference a field in LINQ that is named using a reserved word?

table:UserTypes
Fields:row,name,Type
This code is not working:
Int64 row = 1;
var myType = (from b in dc.UserTypes where b.Row == user.Row select b).Single();
myType.Type = "personalPage";
dc.SubmitChanges();
But, this code does...
dc.ExecuteQuery<UserType >("update dbo.UserType set Type='personalPage' where row={0}",user.Row );
I get this error:
Type the word is a word reserved.i can not user wordType
EDIT
dbml
[Table(Name="dbo.UserType")]
public partial class UserType
{
private long _Row;
private string _Type;
public UserType()
{
}
[Column(Storage="_Row", DbType="BigInt NOT NULL")]
public long Row
{
get
{
return this._Row;
}
set
{
if ((this._Row != value))
{
this._Row = value;
}
}
}
[Column(Storage="_Type", DbType="NVarChar(500) NOT NULL", CanBeNull=false)]
public string Type
{
get
{
return this._Type;
}
set
{
if ((this._Type != value))
{
this._Type = value;
}
}
}
}
Go into your LINQ to SQL DBML mapping and change the mapping for UserType.Type from being to a column named "Type" to a column named "[Type]". You can do this in the designer, or manually.
You can reference it as UserType.#Type in your code.

Custom Column Headers in Data Grid View C# from ArrayList

I am creating a dataGridView which gets its values from an arrayList. To retrieve the values, I have:
public DataSet(String totalCM, String totPM, String hkCM, String hkPM, String sherCM, String sherPM, String hinsCM, String hinsPM, String kassCM, String kassPM, String belleCM, String bellePM)
{
_totalCM = totalCM;
_totalPM = totPM;
_hiddenKnollsCM = hkCM;
_hiddenKnollsPM = hkPM;
_sherCM = sherCM;
_sherPM = sherPM;
_hinsdaleCM = hinsCM;
_hinsdalePM = hinsPM;
_kassonCM = kassCM;
_kassonPM = kassPM;
_belleCM = belleCM;
_bellePM = bellePM;
}
public String TotalCurrentMonth
{
get { return _totalCM; }
}
public String TotalPreviousMonth
{
get { return _totalPM; }
}
public String HiddenKnollsCurrentMonth
{
get { return _hiddenKnollsCM; }
}
public String HiddenKnollsPreviousMonth
{
get { return _hiddenKnollsPM; }
}
public String SherwoodCurrentMonth
{
get { return _sherCM; }
}
public String SherwoodPreviousMonth
{
get { return _sherPM; }
}
public String HinsdaleCurrentMonth
{
get { return _hinsdaleCM; }
}
public String HinsdalePreviousMonth
{
get { return _hinsdalePM; }
}
public String KassonCurrentMonth
{
get { return _kassonCM; }
}
public String KassonPreviousMonth
{
get { return _kassonPM; }
}
public String BelleIsleCurrentMonth
{
get { return _belleCM; ; }
}
public String BelleIslePreviousMonth
{
get { return _bellePM; }
}
}
How do I go about creating custom column headers for this, as they need to have a space? Probably a really dumb question, but could not find much information about this specific issue. I know that you can modify the properties in the collection of column names, but it just seems to create new column header names based off of the accessor methods in the code. Thanks in advance.
Well, if you're using .NET 2+ you can use the DisplayNameAttribute Class.
Use in on your properties to specify the string used in the column headers of your DGV; otherwise the property name will be used (as you see).
And if you're using .NET 2+ you shouldn't be using an ArrayList, use a List<T> instread.

C# StackOverflowException

Problem: I am trying to update a List. If a certain item's ID already exists in the List, I want to add onto that item's quantity. If not, then I want to add another item to the list.
cart = (List<OrderItem>)Session["cart"];
for(int counter = cart.Count-1; counter >= 0; counter--)
{
if (cart[counter].productId == item.productId)
{
cart[counter].productQuantity += item.productQuantity;
}
else if (counter == 0)
{
cart.Add(item);
}
}
cart[counter] and item represent an instance(s) of a custom object of mine. Currently when I finally find a matching ID, everything APPEARS as though it should work, but I get a StackOverflowException thrown in my custom object class.
public int productQuantity
{
get
{
return _productQuantity;
}
set
{
productQuantity = value;
}
}
It gets thrown right at the open-bracket of the "set". Could somebody please tell me what the heck is wrong because I've been going at this for the past 2+ hours to no avail. Thank you in advance.
the problem is in your setter of the productQuantity
it should read:
set
{
_productQuantity= value;
}
edit (naming convention):
public class Vertex3d
{
//fields are all declared private, which is a good practice in general
private int _x;
//The properties are declared public, but could also be private, protected, or protected internal, as desired.
public int X
{
get { return _x; }
set { _x = value; }
}
}
Replace productQuantity = value; with _productQuantity = value; (you're recurring infinitely by calling the setter over and over)
Why not just use this instead?
public int productQuantity { get; set; }
But the flaw was in the _
public int productQuantity {
get {
return _productQuantity;
}
set {
_productQuantity = value;
}
}
cart = (List<OrderItem>)Session["cart"];
int index = cart.Find(OrderItem => OrderItem.productId == item.productId);
if(index == -1) {
cart.Add(item);
} else {
cart[index].productQuantity += item.productQuantity;
}
public int productQuantity
{
get
{
return _productQuantity;
}
set
{
_productQuantity = value; //this should be an assignment to a member variable.
}
}

Categories

Resources