Insert specific elements in ASP:GridView - c#

I have some problem with GridView component. My task is to insert into the gridview data from a class called a book whose number of pages is greater than 100. Class:
public class Knjiga {
public string nazivKnjige { get; set; }
public string imeAutora { get; set; }
public int brStr { get; set; }
public int ID { get; set; }
public Knjiga(string naziv, string ime, int broj, int id) {
nazivKnjige = naziv;
imeAutora = ime;
brStr = broj;
ID = id;
}
}
I try something like this:
List<Knjiga> biblioteka = new List<Knjiga>() {
new Knjiga("Mali Princ", "Hans Kristiansen Andersen", 355, 009),
new Knjiga("Na Drini cuprija", "Ivo Andric", 100, 088),
new Knjiga("Starac i more", "Ernest Hemingvej", 67, 033),
new Knjiga("Covek posle rata", "Dusan Vasiljev", 255, 011),
new Knjiga("Gradinar", "Rabindranat Tagore", 125, 077)
};
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
for (int i = 0; i < biblioteka.Count; i++)
{
if (biblioteka[i].brStr > 100)
{
GridView1.DataSource = biblioteka;
GridView1.DataBind();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < biblioteka.Count; i++)
{
if (biblioteka[i].brStr > 100)
{
GridView1.DataSource = biblioteka;
GridView1.DataBind();
}
}
}
But when I start a project, all the data is inserted into the gridview, regardless of whether its number of pages exceeds 100. Does anyone know how to insert only those objects where the number of pages is greater than 100 ??

Before binding the data, to grid view, prepare the data source based on your business.
You are binding the same data multiple times, as the data binding logic present in for-loop

Related

What is preventing my List data from displaying in my DataGridView?

I was getting my list data into my DataGridView by simply populating a List<> and then assigning the List to the DataGridView's DataSource property, but after changing the column headings to be something other than the names of the class members which comprise the List, the assignation no longer works.
At least, no data displays in the grid.
The "funny" thing is that it still inserts the proper amount of rows (albeit empty) in the grid:
There are 14 "fake" (placeholder) rows that I am putting in the grid at the start. I don't know why changing the text in the column headings throws a spanner into the works.
The only changes I made from when it was working (but had ugly column heading titles) and now is this:
dataGridView1.AutoGenerateColumns = false;
-and the addition of the new columns:
dataGridView1.Columns.Add("MovieTitle", "Title");
. . .
private void frmMain_Load(object sender, EventArgs e)
{
dataGridView1.AutoGenerateColumns = false;
LoadInitialData();
}
private void LoadInitialData()
{
List<MoviesSingleTable> listStartupData = new List<MoviesSingleTable>();
MoviesSingleTable mgdc;
//1
mgdc = new MoviesSingleTable
{
MovieTitle = "The Princess Bride",
IMDBRating = 8.1,
MPAARating = "PG",
durationInMinutes = 98,
YearReleased = "1987",
genres = "", // will add these later
actors = "",
directors = "",
screenwriters = ""
};
listStartupData.Add(mgdc);
. . .
//14
mgdc = new MoviesSingleTable();
mgdc.MovieTitle = "Will Penny";
mgdc.IMDBRating = 7.1;
mgdc.MPAARating = "NR"; // "Approved"
mgdc.durationInMinutes = 108;
mgdc.YearReleased = "1967";
mgdc.genres = "";
mgdc.actors = "";
mgdc.directors = "";
mgdc.screenwriters = "";
listStartupData.Add(mgdc);
dataGridView1.DataSource = listStartupData;
ConfigureGrid();
}
private void ConfigureGrid()
{
dataGridView1.BorderStyle = BorderStyle.Fixed3D;
dataGridView1.Columns.Add("MovieTitle", "Title");
dataGridView1.Columns.Add("IMDBRating", "IMDB");
dataGridView1.Columns.Add("MPAARating", "MPAA");
dataGridView1.Columns.Add("durationInMinutes", "Minutes");
dataGridView1.Columns.Add("YearReleased", "Year");
dataGridView1.Columns.Add("genres", "Genres");
dataGridView1.Columns.Add("actors", "Actors");
dataGridView1.Columns.Add("directors", "Directors");
dataGridView1.Columns.Add("screenwriters", "Screenwriters");
}
The class used is:
public class MoviesSingleTable
{
public string MovieTitle { get; set; }
public double IMDBRating { get; set; }
public string MPAARating { get; set; }
public int durationInMinutes { get; set; }
public string YearReleased { get; set; }
public string genres { get; set; }
public string actors { get; set; }
public string directors { get; set; }
public string screenwriters { get; set; }
}
When adding the columns to the grid with code it will be necessary to set each column’s DataPropertyName to mate with the Class property name you want to display in that column.
Below is a helper method to return a column that sets the columns DataPropertyName.
private DataGridViewTextBoxColumn GetColumnForGrid(string colName, string colHeader, string dataPropertyName) {
DataGridViewTextBoxColumn dgvc = new DataGridViewTextBoxColumn();
dgvc.Name = colName;
dgvc.HeaderText = colHeader;
dgvc.DataPropertyName = dataPropertyName;
return dgvc;
}
Also, I recommend you use a BindingList<T> instead of a List<T>.
Usage…
private void Form1_Load(object sender, EventArgs e) {
BindingList<MoviesSingleTable> data = GetData();
DataGridViewColumn col = GetColumnForGrid("MovieTitle", "Title", "MovieTitle");
dataGridView1.Columns.Add(col);
col = GetColumnForGrid("IMDBRating", "IMDB", "IMDBRating");
dataGridView1.Columns.Add(col);
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = data;
}

Change value in a list that is binded?

I'm pretty new at this. Using Windows Forms in Visual Studio. I am to hammer out a store that has clothes, with stock that can be transferred in or out of the store.
I've gotten as far as to having a class, a list that contains the clothes and their quantities, and I've managed to get them into comboboxes. What I want to do now is to be able to 'buy' new quantities, changing the value in the list.
I'm stumped as to how to change the actual quantities, I'm sure I am missing stuff here.
This is my class:
public class Store
{
public string Clothing { get; set; }
public int Quantity { get; set; }
public Store(string c, int q)
{
Clothing = c;
Quantity = q;
}
And this is my current code:
}
public partial class Form1 : Form
{
List<Store> stock = new List<Store>
{
new Store ("Jeans size S", 1),
new Store ("Jeans size M", 3),
new Store ("Jeans size L", 5)
};
public Form1()
{
InitializeComponent();
}
private void bShow_Click(object sender, EventArgs e)
{
cbStockType.ValueMember = "Clothing";
cbStockType.DisplayMember = "Clothing";
cbStockType.DataSource = stock;
cbStockQnt.ValueMember = "Quantity";
cbStockQnt.DisplayMember = "Quantity";
cbStockQnt.DataSource = stock;
}
private void lblHighlightAdd_Click(object sender, EventArgs e)
{
}
private void bSlctClothing_Click(object sender, EventArgs e)
{
if (cbStockType.SelectedIndex < 0)
{ lblHighlightAdd.Text = "None"; }
else
lblHighlightAdd.Text = cbStockType.SelectedValue.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
string quantityToAdd = tbQntAdd.Text;
int add = Convert.ToInt32(quantityToAdd);
string addToStock = cbStockQnt.SelectedValue.ToString();
int newAmount = Convert.ToInt32(addToStock);
int result = newAmount + add;
foreach (var item in stock)
{
if (item.Clothing == cbStockType.SelectedValue.ToString())
{
item.Quantity = item.Quantity + result;
MessageBox.Show(cbStockQnt.SelectedValue.ToString());
}
}
}
}
}
If you can read this spaghetti junk, I'm stuck at getting the quantity of the selected piece of clothing to change. How do I get it to change the value both in the list and in the combobox?

how to save value in listview from other form

Im having a problem in my listview because whenever I get value in other form it is not adding on the list but when I put breakpoint it have a value but still not adding on my listview.
here is my function in form1 getting values from datagridview
public void dataGridView1_DoubleClick(object sender, EventArgs e)
{
qtyOfOrders orders = new qtyOfOrders();
if (dataGridView1.SelectedRows.Count > 0)
{
String mealname = dataGridView1.SelectedRows[0].Cells[1].Value + String.Empty;
String price1 = dataGridView1.SelectedRows[0].Cells[2].Value + String.Empty;
pts.meal = mealname;
pts.qtyprice = Int32.Parse(price1);
orders.Show();
}
}
here is my function from form2 and will save data in listview in form1
private void OK_Click(object sender, EventArgs e)
{
cashier c = new cashier();
pricetempstorage pts = new pricetempstorage(); //class
int qty = Int32.Parse(QTYNumber.Text);
int totalPrice = qty * pts.qtyprice;
pts.qtynumber = qty;
pts.TotalPrice = totalPrice;
c.listView1.Items.Add(pts.meal);
c.qtyOrder.ListView.Items[0].SubItems.Add(pts.qtynumber.ToString());
c.price111.ListView.Items[0].SubItems.Add(pts.TotalPrice.ToString());
this.Hide();
}
this is my class
namespace jollibee4
{
class pricetempstorage
{
static int qtyNumber;
static int qtyPrice;
static int ListViewCount;
static String Meal;
static int totalprice;
public int TotalPrice
{
get
{
return totalprice;
}
set
{
totalprice = qtyNumber * qtyPrice;
}
}
public int qtynumber
{
get
{
return qtyNumber;
}
set
{
qtyNumber = value;
}
}
public int qtyprice
{
get
{
return qtyPrice;
}
set
{
qtyPrice = value;
}
}
public int listviewCount
{
get
{
return ListViewCount;
}
set
{
ListViewCount = value;
}
}
public String meal
{
get
{
return Meal;
}
set
{
Meal = value;
}
}
}
}
Try adding this code this.listView1.View = View.Details; After the c.listView1.Items.Add(pts.meal);
form1
public List<pricetempstorage> Items { get; private set; }
private void OK_Click(object sender, EventArgs e)
{
cashier c = new cashier();
pricetempstorage pts = new pricetempstorage(); //class
int qty = Int32.Parse(QTYNumber.Text);
int totalPrice = qty * pts.qtyprice;
pts.qtynumber = qty;
pts.TotalPrice = totalPrice;
Items.Add(pts);
this.Hide();
}
Create a shopping cart class where items can be append in list
I assume pricetempstorage is your class of item, its name can be product
public static ShoppingCart GetInstance()
{
if (cart == null)
{
cart = new ShoppingCart();
}
return cart;
}
protected ShoppingCart()
{
Items = new List<pricetempstorage>();
}
You have many architectural and stylistic issues with your program (use of static, capitalization, etc.)--to correct them all would require a very lengthy response.
Your code isn't working because you're creating a new instance of the cashier class, and then you're updating its listView1 object. What I think you're trying to do is update the listView object of Form2. So what you should be doing is grabbing a reference to Form2 and populating its ListView object in your OK_Click event handler...
Just a tip here: Public properties should have an initial capital letter. Your pricetempstorage class needs some work.

Remove and modify a selected item from listbox that uses datasource

I have a GUI that I am creating which reads a .csv file into a listbox and I am trying to remove a country that is selected when the application is running using a button. I have tried multiple codes however nothing works I either get a error message "Items collection cannot be modified when the DataSource property is set." or nothing happens. below is what I have at the moment. I am also trying to modify a selected item using textboxes.
namespace Countries
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private IList<tradingDetails> listOfCountries;
public class tradingDetails
{
public string Country { get; set; }
public string GDP { get; set; }
public string Inflation { get; set; }
public string TB { get; set; }
public string HDI { get; set; }
public string TP { get; set; }
public string Display
{
get
{
return string.Format("Country = {0} --- GDP = {1} --- Inflation = {2} --- TB = {3} --- HDI = {4} --- TP = {5}", this.Country, this.GDP, this.Inflation, this.TB, this.HDI, this.TP);
}
}
}
public static string[] headers { get; set; }
public void load_Click(object sender, EventArgs e)
{
this.listOfCountries = new List<tradingDetails>();
this.listBox1.ValueMember = "Countries";
this.listBox1.DisplayMember = "Display";
this.InsertInfo();
this.listBox1.DataSource = this.listOfCountries;
}
public void InsertInfo()
{
OpenFileDialog browse = new OpenFileDialog();
browse.Multiselect = true;
if (browse.ShowDialog() == DialogResult.OK)
{
string selectedFile = browse.FileName;
const int MAX_SIZE = 5000;
string[] AllLines = new string[MAX_SIZE];
AllLines = File.ReadAllLines(selectedFile);
foreach (string line in AllLines)
{
if (line.StartsWith("Country"))
{
headers = line.Split(',');
}
else
{
string[] columns = line.Split(',');
tradingDetails fileCountry = new tradingDetails
{
Country = columns[0],
GDP = columns[1],
Inflation = columns[2],
TB = columns[3],
HDI = columns[4],
TP = columns[5]
};
this.listOfCountries.Add(fileCountry);
}
}
}
}
private void DataBind()
{
listBox1.BeginUpdate();
listBox1.DataSource = listOfCountries;
listBox1.EndUpdate();
}
private void remove_Click(object sender, EventArgs e)
{
for (int x = listBox1.SelectedIndices.Count - 1; x >= 0; x--)
{
int idx = listBox1.SelectedIndices[x];
listBox1.Items.RemoveAt(idx);
}
}
private void search_Click(object sender, EventArgs e)
{
listBox1.SelectedItems.Clear();
for (int i = 0; i < listBox1.Items.Count; i++)
{
if (listBox1.Items[i].ToString().Contains(textBox1.Text))
{
listBox1.SetSelected(i, true);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox2.Text = listBox1.Items.Count.ToString();
}
}
}
UPDATE
I have tried this however this deletes all the information in the combo box and not an individual item.
private void remove_Click(object sender, EventArgs e)
{
comboBox1.DataSource = null;
comboBox1.Items.Remove(comboBox1.SelectedValue);
comboBox1.DataSource = listOfCountries;
}
You can't remove items from listbox while it's bounded with a source. For a better understanding, you are trying to remove the item, that your listbox is not an owner of, but the source is(that you have set the datasource of listbox).
Instead, you need to remove the item from the datasource itself.
private void remove_Click(object sender, EventArgs e)
{
for (int x = listBox1.SelectedIndices.Count - 1; x >= 0; x--)
{
int idx = listBox1.SelectedIndices[x];
//listBox1.Items.RemoveAt(idx);
listOfCountries.RemoveAt(idx)l
}
listBox1.RefreshItems();
}
Also, as you are trying to clear all the items from your listbox, this not a good approach to iterate every items and remove all. Instead, you should either clear your listOfCountries or set the listbox1datasource as null.

Selected rows of the DataGridView reset after load of dialog

I have one dialog, which based on System.Windows.Forms.Form. It contains one control DataGridView.
I fill this DataGridView, and select any rows. Later call I the method ShowDialog of my form. After appear of form I can see that selected first row of DataGridView, but my desired rows are not selected. How can I resolve this problem? I want no make select in the method OnLoad
Below is my code.
DgvDataSource dgvDs = new DgvDataSource();
DgvForm dgvF = new DgvForm();
dgvF.DataSource = dgvDs;
dgvF.SelectRows(new int[] { 3, 5, 7, 9, 10}); dgvF.ShowDialog();
public class DgvForm : Form
{
public DgvForm()
{
InitializeComponent();
}
DgvDataSource dataSource;
public DgvDataSource DataSource
{
get { return myDataGridView.DataSource; }
set
{
myDataGridView.DataSource = value;
}
}
public void SelectRows(int[] indexes)
{
myDataGridView.ClearSelection();
foreach (DataGridViewRow r in dataGridView1.Rows)
{
r.Cells[0].Selected = indexes.Contains(r.Index);
}
}
}
public class DgvDataSource
{
public BindingList<DgvItem> Items { get; private set; }
public DgvDataSource()
{
InitItems();
}
void InitItems()
{
Items = new BindingList<DgvItem>();
for (int i = 0; i < 20; i++)
{
Items.Add(new DgvItem() { Id = i + 1,
Description = "Description " + (i+1).ToString() });
}
}
}
public class DgvItem
{
public int Id { get; set; }
public string Description { get; set; }
}
Put you SelectRows in the Load Event in the Dialog Form. When you create the instance, set a int[] property:
DgvForm dgvF = new DgvForm();
//this property should be in the Dialog Form
dgvF.Selection = new int[] { 3, 5, 7, 9, 10};
dgvF.ShowDialog();
Luego en el Form:
private int[] selection;
public int[] Selection
{
get { return selection; }
set { selection = value; }
}
private void Form1_Load(object sender, EventArgs e)
{
//Put your code here, to load DataSource and Select Rows.
}

Categories