Grid View check the value is exist? - c#

I have a drop down list "ddlMitchelLandscape2" ,when add button triggers ,i add the selected item value in to gridview.
I am stuck here ,how to check the gridview, before add the value to grid view. The selected item is already exist in grid view or not when the add button is triggered .
Some one help me how to check the value is exist in gridview before add it to gird view please ?
protected void btnAddMitchellLandscape_Click(object sender, EventArgs e)
{
//validate to make sure Mitchell Landscape is entered
if (!ValidateMitchellPage())
return;
Assessment objAssessment = (Assessment)Session[Session_CurrentAssessment];
if (ddlMitchelLandscape2.GetSelectedItemValue > 0)
{
if (lblMitchellID.Text == string.Empty)
{
//add
AssessmentEntity objAssessmentEntity = new AssessmentEntity();
Assessment.tblMitchellLandscapeIDRow row =
objAssessment.tblMitchellLandscapeID.NewtblMitchellLandscapeIDRow();
row.MitchellLandscapeID = ddlMitchelLandscape2.GetSelectedItemValue;
row.MitchellLandscapeName = ddlMitchelLandscape2.GetSelectedItemText;
}
else
{
//Add button not visible when its not a new row
ctrlHeader.ShowError("Error: Unknown error");
return;
}
//refresh data bound table
PopulateMitchellDetailsToForm(ref objAssessment);
//clear after save
btnClearMitchellLandscape_Click(null, null);
}
}
ValidateMitchellPage()
private bool ValidateMitchellPage()
{
litMitchellError.Text = string.Empty;
if (ddlMitchelLandscape2.GetSelectedItemValue <= 0)
litMitchellError.Text = "Please select Mitchell Landscape";
if (litMitchellError.Text.Trim() == string.Empty)
{
litMitchellError.Visible = false;
return true;
}
litMitchellError.Visible = true;
return false;
}
DataBind to grid view
private void PopulateMitchellDetailsToForm(ref Assessment objAssessment)
{
Assessment.tblMitchellLandscapeIDRow[] MlData
= (Assessment.tblMitchellLandscapeIDRow[])objAssessment.tblMitchellLandscapeID.Select("SaveType <> " + Convert.ToString((int)EnumCollection.SaveType.RemoveOnly));
this.gvMitchellLandscape.DataSource = MlData;
this.gvMitchellLandscape.DataBind();
}

You have to check the selected value from the dropdown or combobox in gridview by checking each row.
You can use following code to get row of gridview.
bool isValueExist=False;
for (int i = 0; i < gridview.Rows.Count; i++)
{
String val = gridview.Rows[i].Cells[0].Value.ToString();
if(val == your_drop_down_value)
{
isValueExist=True;
break;
}
}
You have to change the cell number according to your gridview design.

Related

Check through selected items in CheckedListBox and show/ hide columns based on values selected

I am using C# and I need some help. I have DataGridView that I would like to filter (show/ hide columns) based on user selection from the CheckedListBox.
Inside the CheckedListBox, I have listed few items and those are the Column Names from the DataGridView:
All these columns are hidden by default.
CheckedListBox items
Now if user selects THERMAL, I would like to show THERMAL Column in DataGridView. If user deselects THERMAL, I would like to hide THERMAL Column in DataGridView. If user selects/ deselects multiple items, I would like to show/ hide all those items from the DataGridView. I hope this makes sense.
Here is the code that I have:
private void CLB_SHOW_HIDE_SelectedIndexChanged(object sender, EventArgs e)
{
string col = "";
for (int i = 0; i < CLB_SHOW_HIDE.CheckedItems.Count; i++)
{
if (col == "")
{
col = CLB_SHOW_HIDE.GetItemText(CLB_SHOW_HIDE.CheckedItems[i]);
this.DGV_FEATURE.Columns[col].Visible = true;
}
else
{
col += ", " + CLB_SHOW_HIDE.GetItemText(CLB_SHOW_HIDE.CheckedItems[i]);
this.DGV_FEATURE.Columns[col].Visible = false;
}
}
}
Here is the problem... If I remove else statement, I can show All the columns properly only if I go from the bottom up (see my picture above). If I go from top to the bottom, only first item would show. Then I would have to deselect that item and select another one in order for it to show.
If I add else statement like in above code, I get this
Error
Can anyone shed some light on this please?
Just figured out... For anyone that might look for solution similar to this, here is the code:
private void CLB_SHOW_HIDE_SelectedIndexChanged(object sender, EventArgs e)
{
int f = 0;
string qry = "";
for (int i = 0; i < CLB_SHOW_HIDE.Items.Count; i++)
{
if (CLB_SHOW_HIDE.GetItemChecked(i))
{
if (f == 1)
{
qry = CLB_SHOW_HIDE.Items[i].ToString();
this.DGV_FEATURE.Columns[qry].Visible = true;
}
if (f == 0)
{
qry = CLB_SHOW_HIDE.Items[i].ToString();
f = 1;
this.DGV_FEATURE.Columns[qry].Visible = true;
}
}
else
{
qry = CLB_SHOW_HIDE.Items[i].ToString();
this.DGV_FEATURE.Columns[qry].Visible = false;
}
}
}
You are looking for ItemCheck event.
For example, let's say, you have added some columns to DataGridView. Then you can setup checkedListBox and add column names to it. Also add an event handler to handle ItemCheck event:
foreach (DataGridViewColumn c in dataGridView1.Columns)
checkedListBox1.Items.Add(c.Name);
checkedListBox1.ItemCheck += CheckedListBox1_ItemCheck;
Then handle ItemCheck event to show or hide columns:
private void CheckedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
var item = checkedListBox1.GetItemText(checkedListBox1.Items[e.Index]);
dataGridView1.Columns[item].Visible = e.NewValue == CheckState.Checked ? true : false;
}

DevExpress Winform - How to compare data between two gridcontrol on multiple key field

I have 2 gridControl and I wanna change background of cells (rows) that different between 2 gridControl with primary key is multiple field set by user.
Any solution for this problem?
See this example image
In this two query, key field is col1, col2, col3 and col4. Different in col6 and I want to highlight cell that have different value.
This is my current code for RowCellStyle event
private void gvQuery1_RowCellStyle(object sender, RowCellStyleEventArgs e)
{
if (gcQuery2.DataSource == null || lsKey == null || lsKey.Count <= 0)
return;
List<object> id = new List<object>();
foreach (KeyObject key in lsKey)
{
id.Add((sender as GridView).GetRowCellValue(e.RowHandle, key.key1[1].ToString()));
}
for (int i = 0; i < gvQuery2.RowCount; i++)
{
int rowHandle = gvQuery2.GetVisibleRowHandle(i);
bool flgEqual = true;
for (int j = 0; j < lsKey.Count; j++)
{
object v = gvQuery2.GetRowCellValue(rowHandle, gvQuery2.VisibleColumns[int.Parse(lsKey[j].key2[0].ToString())]);
if (id[j] == null && v == null)
continue;
if (!id[j].GetType().Equals(v.GetType()) || !id[j].ToString().Equals(v.ToString()))
{
flgEqual = false;
break;
}
}
if (flgEqual)
{
for (int k = 0; k < (sender as GridView).Columns.Count; k++)
{
if (!(sender as GridView).GetRowCellValue(e.RowHandle, (sender as GridView).Columns[k].FieldName).ToString()
.Equals(gvQuery2.GetRowCellValue(rowHandle, (sender as GridView).Columns[k].FieldName).ToString()))
{
if (e.Column.FieldName.Equals((sender as GridView).Columns[k].FieldName))
e.Appearance.BackColor = Color.Orange;
}
}
break;
}
}
}
Refer this: Customizing Appearances of Individual Rows and Cells
You can implement your functionality using the
GridView.RowCellStyle event. This event is fired for each cell in
a Grid View and thus it has Column and RowHandle parameters
that identify the cell being painted.
I assume that you have fixed number of records in both grid and also the order of the records are same. Then you can try to user same row handle to access the value from the both grid's MainView at RowCellStyle event as below:
using DevExpress.XtraGrid.Views.Grid;
// ...
private void gridView1_RowCellStyle(object sender, RowCellStyleEventArgs e) {
GridView View = sender as GridView;
GridView leftGridView = leftGrid.MainView as GridView; //It is up to you that which viewtype you have used.
if(e.Column.FieldName == "Col5") {
string srcVal= View.GetRowCellDisplayText(e.RowHandle, View.Columns["Col5"]); // You can use GetRowCellValue() method also to get the value from the cell.
string leftGridVal= leftGridView .GetRowCellDisplayText(e.RowHandle, leftGridView .Columns["Col5"]);
if(srcVal != leftGridVal) {
e.Appearance.BackColor = Color.DeepSkyBlue;
e.Appearance.BackColor2 = Color.LightCyan;
}
}
}
Above code snippet is just like a sudo code to direct you to implement the functionality.. Handle this event on that Grid on which you want to color.. Remember to take care about the RowHandle, you have take care about the row index.
Hope this help..
Use the GridView.RowCellStyle event, which enables appearance settings of individual cells to be changed
Please refer this site for your reference
https://www.devexpress.com/Support/Center/Question/Details/Q520842
void gridView1_RowCellStyle(object sender, RowCellStyleEventArgs e)
{
GridView currentView = sender as GridView;
if (e.Column.FieldName == "Customer")
{
bool value = Convert.ToBoolean(currentView.GetRowCellValue(e.RowHandle, "Flag_Customer"));
if (value)
e.Appearance.BackColor = Color.Red;
}
if (e.Column.FieldName == "Vendor")
{
bool value = Convert.ToBoolean(currentView.GetRowCellValue(e.RowHandle, "Flat_Vendor"));
if (value)
e.Appearance.BackColor = Color.Red;
}
}

Copy multiple selected rows from datagridview to textboxes

I have a datagridview named PTable which shows a table from database. I also have a button that functions to copy the data from selected rows to the textboxes I have.
This code that I have right now copies two selected rows from the datagridview but when I only select one row or when I select more than 2 rows, it says that "Index was out of range"
What should happen is that it should copy any number of rows and not only 2 rows
private void button11_Click(object sender, EventArgs e)
{
productid.Text = PTable.SelectedRows[0].Cells[0].Value + string.Empty;
productname.Text = PTable.SelectedRows[0].Cells[1].Value + string.Empty;
unitprice.Text = PTable.SelectedRows[0].Cells[4].Value + string.Empty;
productid2.Text = PTable.SelectedRows[1].Cells[0].Value + string.Empty;
productname2.Text = PTable.SelectedRows[1].Cells[1].Value + string.Empty;
unitprice2.Text = PTable.SelectedRows[1].Cells[4].Value + string.Empty;
}
If a user have not selected two rows, your index 1 (PTable.SelectedRows[1]) is not valid, because the item is not there.
Before you can run this code, you have to check, if the user selected two rows:
if (PTable.SelectedRows.Count == 2)
{
//Your code ...
}
else
{
//Not two rows selected
}
First, make sure SelectionMode of DataGridView to FullRowSelect(Hope you have done it already)
Second, Use foreach or any looping logic to go through each selected rows.
Third, It's always better to write modular code. Write a validation method which returns TRUE or FALSE based on selection of the grid rows.
Now based on returned value you need to continue writing your business logic.
Fourth, Make sure to use NULL checks
So let's start by re-factoring the code.
private void button11_Click(object sender, EventArgs e)
{
If(IsRowOrCellSelected())
{
//loop through selected rows and pick your values.
}
}
I am just writing sample, make sure PTable is accessible.
private boolean IsRowOrCellSelected()
{
if (PTable.SelectedRows.Count > 0)
{
DataGridViewRow currentRow = PTable.SelectedRows[0];
if (currentRow.Cells.Count > 0)
{
bool rowIsEmpty = true;
foreach(DataGridViewCell cell in currentRow.Cells)
{
if(cell.Value != null)
{
rowIsEmpty = false;
break;
}
}
}
if(rowIsEmpty)
return false;
else
return true;
}
Code can be still improved.
To work with varying number of selected rows I suggest the following.
My approach is:
There may be more than 5 rows, that You have to display. First create 3 panels for the TextBoxes. I have named the one for the productids as here. Generate the textboxes from code, this way it's easier to maintain more than 5 selected rows:
// This code goes to the constructor of the class. Not in the button click
List<TextBox> productids = new List<TextBox>();
List<TextBox> productnames = new List<TextBox>();
List<TextBox> unitprices = new List<TextBox>();
for (int i = 0; i < 5; i++)
{
productids.Add(new TextBox { Top = i * 32 });
productnames.Add(new TextBox { Top = i * 32 });
unitprices.Add(new TextBox { Top = i * 32 });
here.Controls.Add(productids[i]);
here2.Controls.Add(productnames[i]);
here3.Controls.Add(unitprices[i]);
}
Than You can in the button click set the value for each selected row:
// This code goes to the button click
// first empty the Textboxes:
foreach (TextBox productid in productids)
{
productid.Text = string.Empty;
}
foreach (TextBox productname in productnames)
{
productname.Text = string.Empty;
}
foreach (TextBox unitprice in unitprices)
{
unitprice.Text = string.Empty;
}
for (int i = 0; i < PTable.SelectedRows.Count; i++)
{
productids[i].Text = PTable.SelectedRows[i].Cells[0].Value.ToString();
productnames[i].Text = PTable.SelectedRows[i].Cells[1].Value.ToString();
// or better... Name the columns
// unitprices[i].Text = PTable.SelectedRows[i].Cells["unitPrices"].Value.ToString();
unitprices[i].Text = PTable.SelectedRows[i].Cells[4].Value.ToString();
}

DropdownList SelectedValue property doesn't accept value during edit operation

I have a cascading dropdownlist inside a gridview which contains 5 columns which are ItemsType, ItemList, UnitPrice, Quantity and Total. Selecting ItemsType in 1st dropdownlist will populate items in 2nd dropdownlist i.e. ItemList which is bound to database.
Problem that I am getting is that when I click Edit button, items in 2nd dropdownlist Itemstype isn't selected though I have assigned the selectedValue.
When I ran the webform in debugging mode I saw that though value has been rightly assigned to dropdownlist.selectedvalue, it isn't accepting the value at all.
The weird thing is that when I click the edit button for the second time after 1st debug, items in dropdownlist are selected correctly.
I have used the following
ddlCarriedItems.SelectedValue = SValue;
Though SValue has values of itemlist, SelectedValue displays none.
Here's the code.
protected void btnEdit_Click(object sender, EventArgs e)
{
try
{
Button btn = (Button)sender;
GridViewRow gv = (GridViewRow)btn.NamingContainer;
string VRM_id = gv.Cells[0].Text;
dc.Company_code = Convert.ToInt32(Session["company_code"].ToString());
dc.Vrm_id = Convert.ToInt32(VRM_id);
DataTable dtVRM_CP = vrmbll.edit_VRM_carried_products(dc);
int rowIndex = 0;
if (dtVRM_CP.Rows.Count > 0)
{
for (int i = 0; i < dtVRM_CP.Rows.Count; i++)
{
DropDownList ddlItemsType = (DropDownList)gvCarriedItems.Rows[rowIndex].Cells[1].FindControl("ddlItemsType");
DropDownList ddlCarriedItems = (DropDownList)gvCarriedItems.Rows[rowIndex].Cells[2].FindControl("ddlCarriedItems");
TextBox txtItemPrice = (TextBox)gvCarriedItems.Rows[rowIndex].Cells[3].FindControl("txtItemPrice");
TextBox txtItemQty = (TextBox)gvCarriedItems.Rows[rowIndex].Cells[4].FindControl("txtItemQty");
TextBox txtItemTotal = (TextBox)gvCarriedItems.Rows[rowIndex].Cells[5].FindControl("txtItemTotal");
ddlItemsType.SelectedIndex = Convert.ToInt32((dtVRM_CP.Rows[i]["items_type"]).ToString());
int itemstype = ddlItemsType.SelectedIndex;
string SValue = dtVRM_CP.Rows[i]["items"].ToString();
if (itemstype == 1)
{
ddlCarriedItems.SelectedValue =SValue;
}
else if (itemstype == 2)
{
ddlCarriedItems.SelectedValue = SValue;
}
else if (itemstype == 3)
{
ddlCarriedItems.SelectedValue = SValue;
}
else
{ }
txtItemPrice.Text = dtVRM_CP.Rows[i]["items_price"].ToString();
txtItemQty.Text = dtVRM_CP.Rows[i]["items_qty"].ToString();
txtItemTotal.Text = dtVRM_CP.Rows[i]["items_total"].ToString();
if (i != (dtVRM_CP.Rows.Count) - 1 && gvCarriedItems.Rows.Count != (dtVRM_CP.Rows.Count))
{
AddNewRow();
}
rowIndex++;
}
}
}
catch
{ }
}
Ok I've found the problem in my code. The thing is that I had to bind dropdownlist everytime before assigning value to ddlCarriedItems.SelectedValue.
I modified my code as following as per #king.code suggestion:
if (itemstype == 1)
{
DataTable dt = vrmbll.select_raw_materials_production(dc);
ddlCarriedItems.DataSource = dt;
ddlCarriedItems.DataValueField = "ID";
ddlCarriedItems.DataTextField = "Name";
ddlCarriedItems.DataBind();
ddlCarriedItems.Items.Insert(0, new ListItem("----- Select -----", "-1"));
ddlCarriedItems.SelectedValue = SValue;
}
But I have no idea why the previous code worked when I ran debugging for 2nd time.

C# Datagridview Checkbox Checked Event - multiple rows?

I have a datagridview with multiple columns and rows.
The first column contains a checkbox.
I want the user to be able to select multiple checkboxes and then perform an action.
For example if they select checkboxes in rows 1 and 2, the data from other columns in rows 1 and 2 can be selected and passed into a messagebox.
I know i need to use the checkbox_changed event to do this. However I am having trouble working out how to do this for multiple rows?
On button Click event do:
static int SelectColumnIndex = 0;
PerformAction_Click(object sender, System.EventArgs e)
{
string data = string.Empty;
foreach(DataGridViewRow row in MyDataGridView.Rows)
{
if(row.Cells[SelectColumnIndex].Value!=null &&
Convert.ToBoolean(row.Cells[SelectColumnIndex].Value) == true)
{
foreach(DataGridViewCell cell in row.Cells)
{
if(cell.OwningColumn.Index!= SelectColumnIndex)
{
data+= (cell.Value + " ") ; // do some thing
}
}
data+="\n";
}
}
MessageBox.Show(data, "Data");
}
If you want the user to click on a button to perform the action, then what you need to handle is the Click event of the button, not the CheckBox Changed event... When the button is clicked, just go through all rows of your DataGridView and perform an action on rows with a checked checkbox.
static int SelectColumnIndex = 0;
PerformAction_Click(object sender, System.EventArgs e)
{
string data = string.Empty;
foreach(DataGridViewRow row in MyDataGridView.Rows)
{
if(row.Cells[SelectColumnIndex].Value != null
&&
Convert.ToBoolean(row.Cells[SelectColumnIndex].Value) == true)
{
foreach(DataGridViewCell cell in row.Cells)
{
if (cell.OwningColumn.Index != SelectColumnIndex)
{
data+= (cell.Value + " ") ; // do some thing
}
}
data+="\n";
}
}
MessageBox.Show(data, "Data");
}
I think you dont need to any event
i solved this problem by this code:
//In Fill DataGridViewEvent :
DataGridViewCheckBoxColumn ChCol = new DataGridViewCheckBoxColumn();
ChCol.Name = "CheckedRow";
ChCol.HeaderText = "انتخاب";
ChCol.Width = 50;
ChCol.TrueValue = "1";
ChCol.FalseValue = "0";
dg.Columns.Insert(0, ChCol);
// In Button Event put these codes:
try
{
MessageBox.Show(row.Cells[2].Value.ToString() + " --> " +
row.Cells["CheckedRow"].Value.ToString());
}
catch
{
// Nothing Act
}
enter code here
Your Output by this parameter :
ItemID --> 0 // For Unchecked Values
ItemID --> 1 // For Checked Values
Now You Can filter the rows that return 1 as value for your action
i tested this code and it work for me

Categories