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;
Related
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.
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();
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();
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.
I have to wrote a DataGridView and filled it programmatically.
I want when the user searches the a word for example key and there is cell which contains it (for example its keyword) just highlight the searched word key in keyword not the all keyword or not the cell nor the row.
Here is the code for filling DataGridView:
private void Fill()
{
try
{
if (dataGridView1 != null)
{
dataGridView1.ColumnCount = 11;
dataGridView1.Columns[0].HeaderText = Resources.Form1_Fill_ID;
dataGridView1.Columns[1].HeaderText = Resources.Form1_Fill_Family;
dataGridView1.Columns[2].HeaderText = Resources.Form1_Fill_Cellphone;
dataGridView1.Columns[3].HeaderText = Resources.Form1_Fill_Phone1;
dataGridView1.Columns[4].HeaderText = Resources.Form1_Fill_Phone2;
dataGridView1.Columns[5].HeaderText = Resources.Form1_Fill_Phone3;
dataGridView1.Columns[6].HeaderText = Resources.Form1_Fill_Fax;
dataGridView1.Columns[7].HeaderText = Resources.Form1_Fill_CompanyName;
dataGridView1.Columns[8].HeaderText = Resources.Form1_Fill_Agency;
dataGridView1.Columns[9].HeaderText = Resources.Form1_Fill_Brands;
dataGridView1.Columns[10].HeaderText = Resources.Form1_Fill_Address;
dataGridView1.Columns[0].Name = Resources.Form1_Fill_ID;
dataGridView1.Columns[1].Name = Resources.Form1_Fill_Family;
dataGridView1.Columns[2].Name = Resources.Form1_Fill_Cellphone;
dataGridView1.Columns[3].Name = Resources.Form1_Fill_Phone1;
dataGridView1.Columns[4].Name = Resources.Form1_Fill_Phone2;
dataGridView1.Columns[5].Name = Resources.Form1_Fill_Phone3;
dataGridView1.Columns[6].Name = Resources.Form1_Fill_Fax;
dataGridView1.Columns[7].Name = Resources.Form1_Fill_CompanyName;
dataGridView1.Columns[8].Name = Resources.Form1_Fill_Agency;
dataGridView1.Columns[9].Name = Resources.Form1_Fill_Brands;
dataGridView1.Columns[10].Name = Resources.Form1_Fill_Address;
}
_conn.ConnectionString = _connectionString;
var cmd = new OleDbCommand("Select * from contacts ", _conn);
_conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
int i = 0;
while (reader != null && reader.Read())
{
if (dataGridView1 != null)
{
dataGridView1.Rows.Add(1);
}
if (dataGridView1 != null)
{
var row = dataGridView1.Rows[i];
row.Cells[Resources.Form1_Fill_ID].Value = reader[0].ToString();
row.Cells[Resources.Form1_Fill_Family].Value = reader[1].ToString();
row.Cells[Resources.Form1_Fill_Cellphone].Value = reader[2].ToString();
row.Cells[Resources.Form1_Fill_Phone1].Value = reader[3].ToString();
row.Cells[Resources.Form1_Fill_Phone2].Value = reader[4].ToString();
row.Cells[Resources.Form1_Fill_Phone3].Value = reader[5].ToString();
row.Cells[Resources.Form1_Fill_Fax].Value = reader[6].ToString();
row.Cells[Resources.Form1_Fill_CompanyName].Value = reader[7].ToString();
row.Cells[Resources.Form1_Fill_Agency].Value = reader[8].ToString();
row.Cells[Resources.Form1_Fill_Brands].Value = reader[9].ToString();
row.Cells[Resources.Form1_Fill_Address].Value = reader[10].ToString();
}
i++;
}
}
catch (Exception ex)
{
return;
}
finally
{
_conn.Close();
}
}
and here is the search code
private void searchBtn_Click(object sender, EventArgs e)
{
// Code to search the alphanumneric Part Number (in Column1 header called "PART NUMBER") and highlihgt the row
foreach (DataGridViewRow row in dataGridView1.Rows)
{
try
{
if (row.Cells[0].Value.ToString().Contains(searchTxt.Text))
//row.Cells[0].Style.ForeColor = Color.Red;
{
var t = row.Cells[0].Value.ToString();
}
if (row.Cells[1].Value.ToString().Contains(searchTxt.Text))
row.Cells[1].Style.ForeColor = Color.Red;
if (row.Cells[2].Value.ToString().Contains(searchTxt.Text))
row.Cells[2].Style.ForeColor = Color.Red;
if (row.Cells[3].Value.ToString().Contains(searchTxt.Text))
row.Cells[3].Style.ForeColor = Color.Red;
if (row.Cells[4].Value.ToString().Contains(searchTxt.Text))
row.Cells[4].Style.ForeColor = Color.Red;
if (row.Cells[5].Value.ToString().Contains(searchTxt.Text))
row.Cells[5].Style.ForeColor = Color.Red;
if (row.Cells[6].Value.ToString().Contains(searchTxt.Text))
row.Cells[6].Style.ForeColor = Color.Red;
if (row.Cells[7].Value.ToString().Contains(searchTxt.Text))
row.Cells[7].Style.ForeColor = Color.Red;
if (row.Cells[8].Value.ToString().Contains(searchTxt.Text))
row.Cells[8].Style.ForeColor = Color.Red;
if (row.Cells[9].Value.ToString().Contains(searchTxt.Text))
row.Cells[9].Style.ForeColor = Color.Red;
if (row.Cells[10].Value.ToString().Contains(searchTxt.Text))
row.Cells[10].Style.ForeColor = Color.Red;
}
catch (Exception)
{
return;
}
}
}
If this search is only depend upon client side loaded data then why don't you suggest to customer use browser search functionality.
If still you have to provide this functionality to customer then why you are going at server side code to do this task.... you can handle this in javascript.
Following are the example Link which explains about how to access datagridview in javascript.
http://www.netomatix.com/development/gridviewclientsideaccess.aspx
http://www.thescarms.com/dotnet/webdatagrid.aspx
It's not possible with standard .NET controls.
You can try Telerik winform suite or similar, which controls allowing to use HTML formatting to highlight only a part of the text.
Do you really need DataGridView? If you use it to display data only, you can also try using WebBrowser control and draw an html table there.
You should also refactor your search code:
for(int i=0; i<11; i++)
{
if (row.Cells[i].Value.ToString().Contains(searchTxt.Text))
row.Cells[i].Style.ForeColor = Color.Red;
}