Display gridview row count based on dropdown selection - c#

I am using this code to take a gridview count and display in a label on page load and works fine.
Page Load:
int rowCount = dtDetails.Rows.Count;
lblTotalRows.Text = rowCount.ToString() + "records found";
I have a dropdown above my gridview and when I select dropdown values the row count have to changed based on the dropdown selected values.
How could I possibly do that in dropdown selected index change
protected void ddlGroup_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dtGroup = DataRepository.GetGroup(ddlGroup.Text);
gvDetails.DataSource = dtGroup;
gvDetails.DataBind();
//Now how could I possible show the respective row counts in the label
}
protected void ddlGroup_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dtDept = DataRepository.GetDept(ddlGroup.Text, ddlDept.Text);
gvDetails.DataSource = dtDept;
gvDetails.DataBind();
//Now how could I possible show the respective row counts of both group and
dept row count since they are cascading dropdowns in the label
}
Any suggestions?

I tend to make a SetData() method so all this kind of code is in one place. So in this instance I would:
protected void SetData(DataTable dtGroup)
{
// Bind the data to the grid
gvDetails.DataSource = dtGroup;
gvODetails.DataBind();
// Show row count
if (!dtGroup.Rows.Count.Equals(0))
lblTotalRows.Text = dtGroup.Rows.Count + " records found";
else
lblTotalRows.Text = "No records found";
}
This way you only have one place that does all the 'bindind' so in your Page_Load you can just call this SetData() method and pass in the datatable, and the same on your SelectedIndexChanged.

Related

C# How do I copy from one data grid to another without overwriting my previous selection?

I have 2 datagrid views with one datatable. I am trying to have a button that when clicked it adds the rows from csv_datagridview to optimal_datagridview. The below works however whenever I deselect an entry in csv_datagridview and hit the button again it clears that selection. I would like to have the selection stick each time.
if (selectedRowCount <= 9)
{
List<object> destList = new List<object>();
foreach (DataGridViewRow row in csv_datagridview.SelectedRows)
destList.Add(row.DataBoundItem);
optimaldataGridView.DataSource = destList;
Thank you so much in advance :)
It is unclear what your exact problem is with the little code you show, but from your statement whenever I deselect an entry in csv_datagridview and hit the button again it clears that selection. I am guessing that if nothing is selected, the data in optimaldataGridView clears when you press the add selected button.
I will assume the csv_datagridview is bound to a table. Your posted code shows the creation of new List destList which you fill with the selected rows from the csv_datagridview. Then you set optimaldataGridView data source to the destList. One issue I see in this picture is that as soon as you leave the if (selectedRowCount <= 9) clause… destList will no longer exist. As a data source for a DataGridView on your form, I would think you would want to keep this List global as long as the form is open. Either way... you are not adding the selected rows, you are simply removing the existing rows and then adding what was selected in csv_datagridview.
I hope the code below will help. I created two DataTables, one for each DataGridView. The csv_datagridview data table is filled with some data, the second data table is left empty. Then simply add the selected rows from the csv_datagridview to the optimaldataGridView’s DataTable… Then refresh optimaldataGridView.
DataTable table1;
DataTable table2;
public Form1() {
InitializeComponent();
csv_datagridview.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
optimaldataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
table1 = GetTable("table1");
table2 = GetTable("table2");
FillTable(table1);
csv_datagridview.DataSource = table1;
optimaldataGridView.DataSource = table2;
}
private void button1_Click(object sender, EventArgs e) {
if (csv_datagridview.SelectedRows.Count > 0) {
foreach (DataGridViewRow row in csv_datagridview.SelectedRows) {
DataRowView dr = (DataRowView)row.DataBoundItem;
table2.Rows.Add(dr.Row.ItemArray[0], dr.Row.ItemArray[1], dr.Row.ItemArray[2]);
}
optimaldataGridView.Refresh();
}
}
private DataTable GetTable(string name) {
DataTable table = new DataTable(name);
table.Columns.Add("col1");
table.Columns.Add("col2");
table.Columns.Add("col3");
return table;
}
private void FillTable(DataTable table) {
for (int i = 0; i < 10; i++) {
table.Rows.Add("R" + i + "C0", "R" + i + "C1", "R" + i + "C2");
}
}
Hope this helps.
Your code is working on my side.
Created a DataTable for Datasource of csv_datagridview.
Selected some rows in this grid.
Clicked the button to copy the selected rows to the
optimaldataGridView
The selected rows are still selected.
public Form1()
{
InitializeComponent();
DataTable dt = new DataTable();
dt.ReadXml(Application.StartupPath + #"\test.xml");
csv_datagridview.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
csv_datagridview.DataSource = dt;
}
private void button1_Click(object sender, EventArgs e)
{
List<object> destList = new List<object>();
foreach (DataGridViewRow row in csv_datagridview.SelectedRows)
destList.Add(row.DataBoundItem);
optimaldataGridView.DataSource = destList;
}
Make sure you have no events attached to the grids that may affect the selection.

How to select a row in a DataGridView programmatically AND trigger DataGridView.SelectionChanged event?

For the life of me I cannot seem to figure this out. I have a long DataGridView (that does not allow MultiSelect) and when a user commits a change to the data, the data from the grid is purged and redrawn (because changes can affect multiple rows, this was the simpler approach). However, when I try to select the row programmatically, it does not also fire the DataGridView.SelectionChanged event, which I use to display data from an array which is correlated to the DataGridView current cell index. When doMagicStuff executes, the values for the wrong index (specifically, index 0) is show.
private void doMagicStuff()
{
int selRow = myDGV.CurrentCell.RowIndex;
myDGV.Rows.Clear();
/*Perform Task, Redraw data*/
myDGV.CurrentCell = myDGV[selRow, 0];
}
private void myDGV_SelectionChanged(object sender, EventArgs e)
{
Label1.Text = myDisplayValue1[myDGV.CurrentCell.RowIndex];
Label2.Text = myDisplayValue2[myDGV.CurrentCell.RowIndex];
TextBox1.Text = myEditValue1[myDGV.CurrentCell.RowIndex];
TextBox2.Text = myEditValue2[myDGV.CurrentCell.RowIndex];
}
Make sure that your client settings and OnSelectedIndexChanged is set like so: (ASP.NET AJAX)
.aspx page
<telerik:RadGrid ID="Grid1" runat="server" OnSelectedIndexChanged="Grid1_SelectedIndexChanged" OnItemDataBound="Grid1_ItemDataBound" OnPreRender="Grid1_PreRender">
<ClientSettings EnablePostBackOnRowClick="true">
<Selecting AllowRowSelect="true"></Selecting>
</ClientSettings>
</telerik:RadGrid>
aspx.cs page
protected void Grid1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = null;
foreach(GridDataItem item in Grid1.SelectedItems)
{
//column name is in doub quotes
value = item["Name"].Text;
}
}
Add a button click to the form to test the selected values in the DataGridView.. double click that button then paste this code in there
foreach (DataGridViewRow row in myDGV.SelectedRows)
{
Label1.Text = //This should be hard coded the only thing that should change dynamically is the TextBox Values
Label2.Text = //This should be hard coded the only thing that should change dynamically is the TextBox Values
TextBox1.Text = row.Cells[0].Value.ToString();//change the 0 or 1 to fit your column Index position
TextBox2.Text = row.Cells[2].Value.ToString();
}
also if you have 4 columns and 4 text boxes then you will assign all of the textbox.Text values within the foreach loop just follow the pattern and increase the index by 1 so 2 textboxes means row.Cells[0] is the first column row.Cells[1] is the second column ...etc

How to get a Telerik Multi column combo box value which is a column in rad grid view?

I want to get the first element of telerik multi combo box which is a column of a telerik grid view
when user selects a row i want to get the first element of that row and pass it to my DB
i've done some thing but i geuss it's not enough
if (Ref_MultiColumnComboBox.MultiColumnComboBoxElement.SelectedIndex >= 0)
{
var tr = Ref_MultiColumnComboBox.MultiColumnComboBoxElement
.EditorControl.Rows[Ref_MultiColumnComboBox.MultiColumnComboBoxElement.SelectedIndex]
.Cells["Id"].Value.ToString();
MessageBox.Show("m= {0}" + " // " + tr);
}
else
{
MessageBox.Show("", "Error");
}
the problem is that when user selects some row or doesn't selectedindex is allways -1
Here is one way to do it for RadMultiColumnComboBox control:
void radMultiColumnComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewDataRowInfo selectedRow = (GridViewDataRowInfo)radMultiColumnComboBox1.SelectedItem;
Console.WriteLine(selectedRow.Cells["Id"].Value.ToString());
}
The SelectedItem provides a reference to the selected row in the inner grid, from where you can access its cells and values.
If GridViewMultiComboBoxColumn is used, then you can use either the ValueChanged event, or the CellValueChangned events to get the row of the currently selected item:
void radGridView1_CellValueChanged(object sender, GridViewCellEventArgs e)
{
RadMultiColumnComboBoxElement mccbEditor = (RadMultiColumnComboBoxElement)e.ActiveEditor;
GridViewDataRowInfo selectedRow = (GridViewDataRowInfo)mccbEditor.SelectedItem;
Console.WriteLine(selectedRow.Cells["Id"].Value.ToString());
}
void radGridView1_ValueChanged(object sender, EventArgs e)
{
RadMultiColumnComboBoxElement mccbEditor = (RadMultiColumnComboBoxElement)radGridView1.ActiveEditor;
GridViewDataRowInfo selectedRow = (GridViewDataRowInfo)mccbEditor.SelectedItem;
Console.WriteLine(selectedRow.Cells["Id"].Value.ToString());
}

Get GridView row index from a template field button

first question:
I have a gridview 'gvSnacks' with a list of snacks and prices. The first column of the gridview is a templatefield with the button 'btnAdd'.
When one of the add buttons is clicked I want it to assign that rows value to an integer so I can retrieve additional data from that row.
This is what I have, but I've hit a dead end.
protected void btnAdd_Click(object sender, EventArgs e)
{
int intRow = gvSnacks.SelectedRow.RowIndex;
string strDescription = gvSnacks.Rows[intRow].Cells[2].Text;
string strPrice = gvSnacks.Rows[intRow].Cells[3].Text;
}
Appreciate any help!
You may need to use the RowCommand Event :
public event GridViewCommandEventHandler RowCommand
This is the MSDN link for this event.
The button must have the CommandName attribute and you can put the value of the row in the command argument :
void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Add")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = ContactsGridView.Rows[index];
// Create a new ListItem object for the contact in the row.
ListItem item = new ListItem();
item.Text = Server.HtmlDecode(row.Cells[2].Text) + " " +
Server.HtmlDecode(row.Cells[3].Text);
// If the contact is not already in the ListBox, add the ListItem
// object to the Items collection of the ListBox control.
if (!ContactsListBox.Items.Contains(item))
{
ContactsListBox.Items.Add(item);
}
}
}

How to filter DataGridView in my application

I have two grids that I set up using the winforms DataGridView wizard. One is bound to a trips table which is my transactions table and the other is bound to my expenses table. I know a little bit of linq2sql and I now have my expense table inserting with the fk(TripId).
What I want to do is filter the expenses grid based on the tripId. I am already retrieving the TripId PK of the currently selected trip so that part is done. I am just not sure how I would do the filtering considering I am using linq but used the built wizards to bind the tables.
Any help would be appreciated!
Edit: I have gotten this far with bluefeet's help below. The problem now is when I do my filter it just clears the grid instead of filtering based on pk. Here is the full code
private void tripsBindingSource_PositionChanged(object sender, EventArgs e)
{
if (dgvTripGrid.CurrentRow != null)
{
//get selected row index
int index = this.dgvTripGrid.CurrentRow.Index;
//get pk of selected row using index
string cellValue = dgvTripGrid["pkTrips", index].Value.ToString();
//change pk string to int
int pKey = Int32.Parse(cellValue);
//int tripPrimKey = getPkRowTrips();
this.tripExpenseBindingSource.Filter = String.Format("tripNo = {0}",
pKey.ToString());
}
}
Sounds like you want to fill your second datagridview based on the selection in your first datagridview. This one way to do it:
On the Load or Search of my first datagridview, use the event
DataBindingComplete which then populates the second datagridview
based on the id of the record selected in the first datagridview.
Then if the selection in the first datagridview changes, I use the
event on the BindingSource_PositionChanged to repopulate the second
grid.
Code Sample
// this populates the grid.
private void SearchButton_Click(object sender, EventArgs e)
{
// your code to load your grid goes here
}
private void DataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
var drv = datagridview1bindingSource.Current as DataRowView;
if(drv != null)
// your method to load datagridview2 goes here if the selected row is not null
LoadDataGridView2();
}
private void LoadDataGridView2()
{
//populate datagridview2 using the selected row id from datagridview1
}
// finally when the position is changed on the datagridview1 binding source, then re-populate // the datagridview2
private void datagridview2BindingSource_PositionChanged(object sender, EventArgs e)
{
LoadDataGridView2();
}
this is a basic way to populate a second grid based on the selection in the first.
Edit:
Your comment says that you are filling the datagridview with all expenses, so to filter you will want to use the Filter property on the BindingSource for the datagridview. The Filter property allows you to view a subset of the DataSource.
Example from MSDN:
private void PopulateDataViewAndFilter()
{
DataSet set1 = new DataSet();
// Some xml data to populate the DataSet with.
string musicXml =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<music>" +
"<recording><artist>Coldplay</artist><cd>X&Y</cd></recording>" +
"<recording><artist>Dave Matthews</artist><cd>Under the Table and Dreaming</cd></recording>" +
"<recording><artist>Dave Matthews</artist><cd>Live at Red Rocks</cd></recording>" +
"<recording><artist>Natalie Merchant</artist><cd>Tigerlily</cd></recording>" +
"<recording><artist>U2</artist><cd>How to Dismantle an Atomic Bomb</cd></recording>" +
"</music>";
// Read the xml.
StringReader reader = new StringReader(musicXml);
set1.ReadXml(reader);
// Get a DataView of the table contained in the dataset.
DataTableCollection tables = set1.Tables;
DataView view1 = new DataView(tables[0]);
// Create a DataGridView control and add it to the form.
DataGridView datagridview1 = new DataGridView();
datagridview1.AutoGenerateColumns = true;
this.Controls.Add(datagridview1);
// Create a BindingSource and set its DataSource property to
// the DataView.
BindingSource source1 = new BindingSource();
source1.DataSource = view1;
// Set the data source for the DataGridView.
datagridview1.DataSource = source1;
//The Filter string can include Boolean expressions.
source1.Filter = "artist = 'Dave Matthews' OR cd = 'Tigerlily'";
}
I use this type of Filter to show data based on account. For an account, I have a textbox when the user places the account number and I use the TextChanged Event to apply the filter. Then I have a button that is used to remove the Filter from the binding source.
You can apply the same thing to your expense datagridview using the tripid from your first datagridview.

Categories

Resources