Remove selected item in combobox - c#

I want to remove a selected item in my combobox
I have here a code upon form load, I am filling list items on combobox from database.
private void LoadComboField()
{
//string test = "<ROOT><DATA FieldGroup=\"PAYMENT_VIEW4\" FieldDescription=\"PNAME\" Output=\"1\" Filter=\"1\" FieldName=\"PATIENTNAME\" DataType=\"STRING\"/><DATA FieldGroup=\"PAYMENT_VIEW4\" FieldDescription=\"MEMID\" Output=\"1\" Filter=\"1\" FieldName=\"MEMBERID\" DataType=\"STRING\"/></ROOT>";
ReadXMLData(XMLDOC, dsCombo);
// ReadXMLData(test, dsCombo);
dt = dsCombo.Tables[0];
DataView dv1 = new DataView(dsCombo.Tables[0]);
this.cmbField.Items.Clear();
this.cmbField.DataSource = dv1;
this.cmbField.DisplayMember = "FieldDescription";
this.cmbField.ValueMember = "FieldName";
}
Then I have this code on SelectedValueChanged
private void cmbField_SelectedValueChanged(object sender, EventArgs e)
{
DataGridViewRow GridRowLoc = this.dgvFilter.CurrentRow;
AddGrid(iRowIdx);
int iRowCount = this.dgvFilter.RowCount - 1;
//this.dgvFilter.CurrentRow.IsNewRow
//if (GridRowLoc.IsNewRow) continue;
// MessageBox.Show(this.dgvFilter.RowCount.ToString());
if (this.cmbField.Text != "System.Data.DataRowView")
{
this.dgvFilter.Rows[iRowIdx].Cells["ColumnFieldName"].Value = this.cmbField.Text;
this.dgvFilter.Rows[iRowIdx].Cells["FieldName"].Value = this.cmbField.SelectedValue;
if (iRowCount <= iRowIdx)
{
DataRow drow = dttable.NewRow();
drow["ColumnNames"] = this.cmbField.Text;
drow["FieldName"]= this.cmbField.SelectedValue;
drow["Alias"]=string.Empty;
drow["DataType"]=string.Empty;
drow["Outputs"]=false;
drow["SortType"]=string.Empty;
drow["SortOrder"]=string.Empty;
drow["GroupBy"]=string.Empty;
drow["Filter"]=string.Empty;
drow["Or1"]=string.Empty;
drow["Or2"]=string.Empty;
drow["Or3"]=string.Empty;
drow["Or4"]=string.Empty;
drow["Or5"]=string.Empty;
drow["Or6"]=string.Empty;
drow["Or7"]=string.Empty;
drow["Or8"]=string.Empty;
drow["Or9"]=string.Empty;
drow["Or10"]=string.Empty;
dttable.Rows.Add(drow);
}
else
{
int irow = 0;
foreach (DataRow dr in dttable.Rows)
{
if (irow == iRowIdx)
{
dr["ColumnNames"] = this.cmbField.Text;
dr["FieldName"] = this.cmbField.SelectedValue;
}
irow++;
}
}
CheckAlias(iRowIdx, this.cmbField.Text, dgvFilter);
checkcellvalue(this.cmbField.Text, iRowIdx);
CheckSorting();
if (bGroupBySelected == true)
{
this.dgvFilter.Rows[iRowIdx].Cells["GroupBy"].Value = "Group By";
}
this.dgvFilter.DataSource = dttable;
dsFilter.AcceptChanges();
this.cmbField.Visible = false;
}
// checkcellvalue(this.cmbField.Text, iRowIdx);
//MessageBox.Show(arr_Filter[0]);
CheckoutputEnable();
}
I have this code in SelectedIndexChanged
try
{
DataTable dt1 = new DataTable();
DataRowView oDataRowView = cmbField.SelectedItem as DataRowView;
string sValue = string.Empty;
if (oDataRowView != null)
{
sValue = oDataRowView.Row["FieldDescription"] as string;
}
//int count = dttable.Rows.Count - 1;
ComboBox comboBox = (ComboBox)sender;
// Save the selected employee's name, because we will remove
// the employee's name from the list.
string selectedEmployee = (string)sValue;
int count = 0;
int resultIndex = -1;
// Call the FindStringExact method to find the first
// occurrence in the list.
resultIndex = cmbField.FindStringExact(selectedEmployee);
// Remove the name as it is found, and increment the found count.
// Then call the FindStringExact method again, passing in the
// index of the current found item so the search starts there
// instead of at the beginning of the list.
while (resultIndex != -1)
{
cmbField.Items.RemoveAt(resultIndex);
count += 1;
resultIndex = cmbField.FindStringExact(selectedEmployee,
resultIndex);
}
// Update the text in Textbox1.
txtName.Text = txtName.Text + "\r\n" + selectedEmployee + ": "
+ count;
}
//}
catch (Exception ex)
{
}
But it throws an exception, say that "items collection cannot be modified when the datasource property is set." I don't know how to fix this exception error, I think that's my only problem when removing an item on the combobox.
Please do help me on this one. Thanks in advance!

Use a BindingSource for your DataSource and CurrentItemChanged to react of changed items in CBO:
this.source = new BindingSource();
this.source.DataSource = loDs.Tables[0];
this.cmbField.DataSource = this.source;
this.source.CurrentItemChanged += source_CurrentItemChanged;
Example for eventHandler:
private void source_CurrentItemChanged(object sender, EventArgs e)
{
System.Data.DataRowView view = this.source.Current as System.Data.DataRowView;
if (view != null)
{
System.Diagnostics.Debug.WriteLine(view[0].ToString());
}
}
You can remove an item from the source like this:
this.source.RemoveAt(this.source.Find("FieldName", "PATIENTNAME"));
Show Details: A Detailed Data Binding Tutorial

You can't modify the Items collection when it comes from / is bound to a DataSource. Instead you need to modify the DataSource itself.
To delete the SelectedItem from the DataSource you can try this:
DataRowView item = cmbField.SelectedItem as DataRowView;
if (item != null) item.Delete();

Related

Can't get gridview dynamic label ID but textboxes are fine

Here is how i get the values from the gridview controllses, as you can see i do the same way for the label as the textbox, except all textboxes get value and label doesn't and i can't find anything different in the code. The function fillGrid() is just a skeleton for the table to fill it first before placing controllers on it
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
var Column1TextBoxes = Request.Form.AllKeys.Where(k => k.Contains("lblIdDetComp")).ToList(); // Gridview Column 1
var Column2TextBoxes = Request.Form.AllKeys.Where(k => k.Contains("txtComponente")).ToList(); // Gridview Column 2
var Column3TextBoxes = Request.Form.AllKeys.Where(k => k.Contains("txtBase")).ToList(); // Gridview Column 3
var Column4TextBoxes = Request.Form.AllKeys.Where(k => k.Contains("txtComprimento")).ToList(); // Gridview Column 4
if (Request.Form[Column1TextBoxes[j]] != "") comp[j].ID = Convert.ToInt32(Request.Form[Column1TextBoxes[j]]); // Column1 values
else break;
if (Request.Form[Column2TextBoxes[j]] != "") comp[j].Nome = Request.Form[Column2TextBoxes[j]]; // Column2 values
else break;
if (Request.Form[Column3TextBoxes[j]] != "") comp[j].Base = Request.Form[Column3TextBoxes[j]]; // Column3 values
else break;
if (Request.Form[Column4TextBoxes[j]] != "") comp[j].Comprimento = Convert.ToDouble(Request.Form[Column4TextBoxes[j]]); // Column4 values
else break;
j++;
}
}
private void fillGrid()
{
int rowCount = 0;
if (ViewState["rowCount"] != null)
{
rowCount = Convert.ToInt32(ViewState["rowCount"]);
}
DataTable dt = new DataTable();
dt.Columns.Add("IdDetComp",typeof(string));
dt.Columns.Add("Componente", typeof(string));
dt.Columns.Add("Base", typeof(string));
dt.Columns.Add("Comprimento", typeof(string));
for (int i = 0; i < rowCount; i++)
{
dt.Rows.Add("","", "", "");
}
GridView1.DataSource = dt;
GridView1.DataBind();
upDetComps.Update();
}
This is where I add the information to the gridview
int i = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false;
if (e.Row.RowType == DataControlRowType.DataRow)
{
Componente[] Comp = (Componente[])ViewState["Componente"];
if (i < Convert.ToInt32(txtNumComps.Text))
{
Label lblIdDetComp = new Label();
lblIdDetComp.ID = "lblIdDetComp" + (i + 1).ToString();
if (Comp[i] != null) lblIdDetComp.Text = Comp[i].ID.ToString();
TextBox txtComponente = new TextBox();
txtComponente.ID = "txtComponente" + (i + 1).ToString();
if (Comp[i] != null) txtComponente.Text = Comp[i].Nome;
TextBox txtBase = new TextBox();
txtBase.ID = "txtBase" + (i + 1).ToString();
if (Comp[i] != null) txtBase.Text = Comp[i].Base;
TextBox txtComprimento = new TextBox();
txtComprimento.ID = "txtComprimento" + (i + 1).ToString();
if (Comp[i] != null)
{
if (Comp[i].Comprimento != 0)
txtComprimento.Text = Comp[i].Comprimento.ToString();
else
txtComprimento.Text = "";
}
e.Row.Cells[0].Controls.Add(lblIdDetComp);
e.Row.Cells[1].Controls.Add(txtComponente);
e.Row.Cells[2].Controls.Add(txtBase);
e.Row.Cells[3].Controls.Add(txtComprimento);
i++;
}
}
}
My guess would be this is because by default, the Label.AutoSize property is false:
Property Value
Boolean
true if the control adjusts its width to closely fit its contents; otherwise, false.
When added to a form using the designer, the default value is true. When instantiated from code, the default value is false.
So the text is there, it's just size (0,0).
Try setting
lblIdDetComp.AutoSize = true;

Check if the selected dataGridView row is bold

I have a piece of that requires to change to regular font and remove from a tracker. I need it check if the row is bold but its failing.
private void clientDataGridView_SelectionChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in clientDataGridView.SelectedRows)
{
if (row.DefaultCellStyle.Font.Style == FontStyle.Bold)
{
row.DefaultCellStyle.Font = new Font(DefaultFont, FontStyle.Regular);
new_tracker --;
}
idtxt.Text = row.Cells[0].Value.ToString();
emailtxt.Text = row.Cells[1].Value.ToString();
nametxt.Text = row.Cells[2].Value.ToString();
packagetxt.Text = row.Cells[3].Value.ToString();
notificationToolStripStatusLabel.Text = "0 new notifications";
}
}
I think you need a few extra checks:
if (row == null) result = "row is null";
else if (!row.HasDefaultCellStyle) result = "no row style"; // this helps!
else if (row.DefaultCellStyle.Font == null) result = "no font"; // may work without
else if (row.DefaultCellStyle.Font.Bold) result = "bold";
I found this to work for rows, where I had actually set the HasDefaultCellStyle.

Save checked row of one dataGrid into another dataGrid

I have a simple datagrid which Stores the data returned in json format in it. I have added unbound checkbox column to it. Now I want to Store only the checked rows in another datagrid. How should I proceed.
My Code
protected void BtnSave_Click(object sender, EventArgs e)
{
foreach (DataGridItem item in this.gv1.Items)
{
CheckBox chkBox =
(CheckBox)item.FindControl("ChkRows");
//If it's selected then add it to our new Datagrid
if (chkBox != null && chkBox.Checked)
{
//save
}
}
}
datasource for 1st grid
SearchAPIRequest.defaultApiKey = "samplekey";
SearchAPIRequest request = new SearchAPIRequest(rawName: txtUser.Text);
try
{
SearchAPIResponse response = request.Send();
DataTable dt = new DataTable();
dt.Columns.Add("Website");
dt.Columns.Add("first");
dt.Columns.Add("last");
dt.Columns.Add("jobs");
dt.Columns.Add("dobs");
dt.Columns.Add("educations");
dt.Columns.Add("addresses");
dt.Columns.Add("images");
dt.Columns.Add("URL");
for (int i = 0; i < response.Records.Count; i++)
{
DataRow dr = dt.NewRow();
dr["Website"] = response.Records[i].Source.Domain;
dr["First"] = response.Records[i].Names[0].First;
dr["Last"] = response.Records[i].Names[0].Last;
dr["jobs"] = response.Records[i].Jobs.Count > 0 ? response.Records[i].Jobs[0].Display: "";
dr["dobs"] = response.Records[i].DOBs.Count > 0 ? response.Records[i].DOBs[0].DateRange.Start.ToString() : "";
dr["images"] = response.Records[i].Images.Count> 0 ? response.Records[i].Images[0].Url:"";
dr["educations"] = response.Records[i].Educations.Count > 0 ? response.Records[i].Educations[0].Display : "";
dr["addresses"] = response.Records[i].Addresses.Count > 0 ? response.Records[i].Addresses[0].Display: "";
dr["URL"] = response.Records[i].Source.Url;
dt.Rows.Add(dr);
}
gv1.DataSource = dt;// response.Records[0].AllFields.ToList();
gv1.DataBind();

Multiple selection from one GridView and display data in another GridView

I am having problem with GridView on row command and stack up the data in another GridView:
private List<DistributionStandardPackingUnitItems> tempDistSPUI
{
get
{
if (ViewState["tempDistSPUI"] == null)
{
return new List<DistributionStandardPackingUnitItems>();
}
else
{
return (List<DistributionStandardPackingUnitItems>)ViewState["tempDistSPUI"];
}
}
set
{
ViewState["tempDistSPUI"] = value;
}
}
protected void gvSPU_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
//Get selected standard packing name
int rowNo = int.Parse(e.CommandArgument.ToString());
SPUname = this.gvSPU.DataKeys[rowNo].Value.ToString();
lblSPUname.Text = SPUname;
//Get the record from view state
itemList = tempDistSPUI;
itemList = packBLL.getAllDistSPUItemByDistributionIDnSPUName(distributionID, SPUname);
gvFinalised.DataSource = itemList;
gvFinalised.DataBind();
//Save the last record to view state
this.tempDistSPUI = itemList;
}
Let's say when I first selected a row from gvSPU, it returns an itemList filled with data and display in gvFinalised. What I am trying to do is if I selected another row from gvSPU, the previous records in gvFinalised will still there and stack up another itemList from the secondly selected row instead of wiping up the record previously and display the latest itemList data.
I am using viewState but it does not work.
EDIT
protected void lbnAdd_Click(object sender, EventArgs e)
{
List<DistributionStandardPackingUnitItems> prodVariantDetail = new List<DistributionStandardPackingUnitItems>();
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
// get the last product variant IDs from ViewState
prodVariantIDList = this.SelectedVariantDetailIDs;
foreach (RepeaterItem ri in Repeater1.Items)
{
GridView gvProduct = (GridView)ri.FindControl("gvProduct");
foreach (GridViewRow gr in gvProduct.Rows)
{
CheckBox cb = (CheckBox)gr.FindControl("cbCheckRow");
//Prevent gvFinalised to store duplicate products
if (cb.Checked && !prodVariantIDList.Any(i => i == gvProduct.DataKeys[gr.RowIndex].Value.ToString()))
{
// add the corresponding DataKey to idList
prodVariantIDList.Add(gvProduct.DataKeys[gr.RowIndex].Value.ToString());
}
}
}
for (int i = 0; i < prodVariantIDList.Count; i++)
{
prodVariantDetail.Add(packBLL.getProdVariantDetailByID(prodVariantIDList[i]));
}
//Check if itemList and prodVariantDetail list contains any duplicate records
var Gdupes = itemList.GroupBy(x => new { x.id }).Where(x => x.Skip(1).Any()).ToList();
List<DistributionStandardPackingUnitItems> dupes = Gdupes.SelectMany(x => x).ToList();
prodVariantDetail = itemList.Except(dupes).ToList();
gvFinalised.DataSource = prodVariantDetail;
gvFinalised.DataBind();
foreach (GridViewRow gr in gvFinalised.Rows)
{
//Get the product packaging quantity by productName
string name = gr.Cells[1].Text;
int productQuantity = packBLL.getProductQuantityByName(name, distributionID);
TextBox tb = (TextBox)gr.Cells[5].FindControl("tbQuantity");
if (productQuantity == 0)
{
tb.Text = productQuantity.ToString();
}
else
{
tb.Text = (productQuantity / packagesNeeded).ToString();
}
}
// save prodVariantIDList to ViewState
this.SelectedVariantDetailIDs = prodVariantIDList;
}
private List<string> SelectedVariantDetailIDs
{
get
{
if (ViewState["SelectedVariantDetailIDs"] == null)
{
return new List<string>();
}
else
{
return (List<string>)ViewState["SelectedVariantDetailIDs"];
}
}
set
{
ViewState["SelectedVariantDetailIDs"] = value;
}
}
The problem is the following lines:
//Get the record from view state
itemList = tempDistSPUI;
// here itemList will be replaced
itemList = packBLL.getAllDistSPUItemByDistributionIDnSPUName(distributionID, SPUname);
First you assign tempDistSPUI from ViewState to itemList, but then you replace itemList at the next line. You need to add the elements returned from packBLL.getAllDistSPUItemByDistributionIDnSPUName to itemList instead of replacing itemList. Here's what I would do using List.AddRange Method:
itemList = tempDistSPUI;
// add the returned elements to itemList
itemList.AddRange(packBLL.getAllDistSPUItemByDistributionIDnSPUName(distributionID, SPUname));
UPDATE
To prevent duplication with the previous elements:
itemList = tempDistSPUI;
List<DistributionStandardPackingUnitItems> itemListNew = new List<DistributionStandardPackingUnitItems>();
itemListNew = packBLL.getAllDistSPUItemByDistributionIDnSPUName(distributionID, SPUname);
// get all previous IDs in a List<int>
List<int> previousIDs = itemList.Select(x => x.id).ToList();
// filter itemListNew and add the elements to itemList
itemList.AddRange(itemListNew.Where(x => !previousIDs.Contains(x.id));

Loading Comboboxes and Setting its value in each row in Datagridview

I am displaying the data in datagridview when user enters PickingNoteNo in the textbox.Then i am adding two comboxes to the Datagridview programatically and setting their respective Datasource.But the data is not displayed in the Comboboxes.can you please tell me changes in my code.
private void LoadDeliveryNoteDetails(string PickingNoteNo)
{
dtDeliveryNoteDetails = new DataTable();
try
{
using (QuotationBusiness objQuotationBusiness = new QuotationBusiness())
{
dtDeliveryNoteDetails = objQuotationBusiness.GetDeliveryNoteDetails(PickingNoteNo);
}
if (dtDeliveryNoteDetails != null)
{
gvDeliveryNoteDetails.DataSource = dtDeliveryNoteDetails;
HideGridViewColumns();
LoadCustomerDetails();
LoadDeliveryDetails();
LoadFreightDetails();
LoadPackagingTypeDetails();
LoadShippingBoxDetails();
}
}
catch (Exception ex)
{
}
}
private void HideGridViewColumns()
{
foreach (DataGridViewColumn column in gvDeliveryNoteDetails.Columns)
{
if (column.Name != "ItemCode" && column.Name != "Quantity" && column.Name != "Description" && column.Name != "BatchNo"
&& column.Name != "ExpiryDate" && column.Name != "Packaging Type")
{
column.Visible = false;
}
}
}
private void LoadPackagingTypeDetails()
{
DataGridViewComboBoxColumn cmbpackingtype = new DataGridViewComboBoxColumn();
cmbpackingtype.Name = "cmbPackingTypes";
cmbpackingtype.HeaderText = "Packaging Type";
gvDeliveryNoteDetails.Columns.Add(cmbpackingtype);
using (QuotationBusiness objQB = new QuotationBusiness())
{
DataTable dtPackingTypes = objQB.GetPackagingTypeDetails();
if (dtPackingTypes != null)
{
DataRow row = dtPackingTypes.NewRow();
row["PackageType"] = "Select";
row["PackageTypeID"] = 0;
dtPackingTypes.Rows.InsertAt(row, 0);
cmbpackingtype.ValueMember = "PackageTypeID";
cmbpackingtype.DisplayMember = "PackageType";
cmbpackingtype.DataSource = dtPackingTypes;
cmbpackingtype.DisplayIndex = 0;
}
}
}
private void LoadShippingBoxDetails()
{
DataGridViewComboBoxColumn cmbBox = new DataGridViewComboBoxColumn();
cmbBox.Name = "cmbBoxNos";
cmbBox.HeaderText = "Box No";
gvDeliveryNoteDetails.Columns.Add(cmbBox);
using (EmployeeMasterBusiness objEmp = new EmployeeMasterBusiness())
{
DataTable dtBoxNos = objEmp.GetDepartmentDetails();
if (dtBoxNos != null)
{
DataRow row = dtBoxNos.NewRow();
row["DeptName"] = "Select";
row["DeptID"] = 0;
dtBoxNos.Rows.InsertAt(row, 0);
cmbBox.DataSource = dtBoxNos;
cmbBox.DisplayMember = "DeptName";
cmbBox.ValueMember = "DeptID";
}
}
}
After setting the datasource in every Row there is PackingID and ShippingID and we need to set the Comboxes Selected value to PackingID for cmbpackingtype ComboBox and ShippingID for cmbBox.Later we can select a new value from the comboboxes and save the data to Database.
1) How do I populate data in Comboboxes.
2) How do i get the selected value from the combobox.
Also there is one more requirement.If the value is selected in the Combobox i.e cmbpackingtype (data like Cartons,Pallets,Boxes) then I need to load the Combox cmbBox depending on PackingID.
Thanks.

Categories

Resources