I am trying to implement a checkbox within gridview,
The job of this checkbox is to verify a record,
When this verify button is pressed, all items with a checked checkbox are inputted into the database
This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cbox = ((CheckBox)row.FindControl("Verify"));
if (cbox.Equals(true))
{
String DraftsText = ((TextBox)row.FindControl("numDrafts")).Text;
String TCtext = ((TextBox)row.FindControl("numTC")).Text;
if (row.RowType == DataControlRowType.DataRow)
{
//Header trs = new Header();
// GridView1.Rows[0].FindControl("numTC");
if (TCtext != "" && DraftsText != "")
{
// try
// {
string date = row.Cells[4].Text;
DateTime dateTime = Convert.ToDateTime(date);
string dateFormatted = dateTime.ToString("d-MMM-yy");
string unit = row.Cells[5].Text;
string currency = row.Cells[6].Text;
string totalFC = row.Cells[7].Text;
string totalDC = row.Cells[8].Text;
int d = Convert.ToInt32(DraftsText);
int tc = Convert.ToInt32(TCtext);
hdr = new Header(d, tc, dateFormatted, unit, currency, totalFC, totalDC);
hdr.InsertFCTC(hdr);
}
}
}
}
}
I might be going at this the wrong way but in the if (cbox.Equals(true))
its giving me an exception: Object reference not set to an instance of an object.
Any idea what i can do to solve this?
Many Thanks
This if (cbox.Equals(true)) should be if (cbox.Checked)
Since your cbox is a checkbox object it can't be used to compare, so you have to use the cbox Checked Property, which will return true/false
You receive a NullPointerException because the suggested checkbox wasn't found! Or the direct cast into an instance of type CheckBox doesn't worked as expected.
Change your code to something like this and retry:
CheckBox cbox = ((CheckBox)row.FindControl("Verify"));
if (cbox != null && cbox.Checked)
{
....
}
Related
I am currently getting data from database, then if i checked the checkbox more than 2 rows, it will sum up the total of SENDQTY and send the details from GridView3 to GridView4. Now how can i check if the STOCKCODE from the 2 rows is different, it will prompt error message?
protected void showGridView()
{
int match = 0;
int total = 0;
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[9] { new DataColumn("DODetailID"), new DataColumn("SALESORDERNO"), new DataColumn("STOCKCODE"), new DataColumn("SENDQTY"), new DataColumn("scanflag"), new DataColumn("REJECT"), new DataColumn("DispatchOrderID"), new DataColumn("DispatchDATE"), new DataColumn("DELORDERNO") });
foreach (GridViewRow row in GridView3.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox CheckBox1 = (row.Cells[0].FindControl("CheckBox1") as CheckBox);
//int qty = Convert.ToInt32(row.Cells[4].Text);
if (CheckBox1.Checked)
{
string DODetailID = (row.Cells[1].FindControl("DODetailID") as Label).Text;
string SALESORDERNO = (row.Cells[2].FindControl("SALESORDERNO") as Label).Text;
string STOCKCODE = (row.Cells[3].FindControl("STOCKCODE") as Label).Text;
int SENDQTY = Convert.ToInt32((row.Cells[4].FindControl("SENDQTY") as Label).Text);
CheckBox scanflag = (row.Cells[5].FindControl("scanflag") as CheckBox);
string REJECT = (row.Cells[6].FindControl("REJECT") as Label).Text;
string DispatchOrderID = (row.Cells[7].FindControl("DispatchOrderID") as Label).Text;
string DispatchDATE = (row.Cells[8].FindControl("DispatchDATE") as Label).Text;
string DELORDERNO = (row.Cells[9].FindControl("DELORDERNO") as Label).Text;
Session["STOCKCODE"] = STOCKCODE.ToString();
dt.Rows.Add(DODetailID, SALESORDERNO, STOCKCODE, SENDQTY, scanflag, REJECT, DispatchOrderID, DispatchDATE, DELORDERNO);
match++;
total = total + SENDQTY;
GridView4.DataSource = dt;
GridView4.DataBind();
}
}
}
}
protected void btnContinue_Click(object sender, EventArgs e)
{
showGridView();
mp3.Show(); // this is showing GridView4
}
you need to run two for each loops. Run the for/each loop on the data first time in which you count check boxes (and stock code). You can then in code decide to run/use your existing loop.
Collection MyCheckList = New Collection;
Boolean ListBad = false;
foreach (GridViewRow row in GridView3.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox CheckBox1 = (row.Cells[0].FindControl("CheckBox1") as CheckBox);
Label txtStock = (row.Cells[0].FindControl("STOCKCODE") as Label);
if CheckBox.Checked {
if MyCheckList.Contains(txtStock.Text) {
ListBad = true;
Exit for;
else
ListBad.Add(txtSTock)
}
etc. etc. etc
etc. etc.
In other words, run a test/loop over the data - put the stockcode into a collection if checked, and if such a stockcode already exists, then you know more then 1 checked of a given stock exists, and thus your flag ListBad = true when you finish that loop process.
You could also add the collection idea to your existing loop. And upon exit, you know if more then one stockcode was checked. So you probably don't need a separate first loop, but you do have to "build up" a list of checked + stockcodes if you checking for an already existing stock code. So build up a checked list in that collection and thus you know if a stockcode been used + checked in that list more then once.
I have a parent and child gridview setup. on the OnRowDataBound event I need the value of a parent gridview cell. this is not the DataKeys of the parent Gridview. I have commented out some of the things I have tried, but not getting quite there. I think the last two lines are close, but I am not sure what the correct syntax should be.
gvCustomers is the parentGV.
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string requestId = gvCustomers.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvOrders = e.Row.FindControl("gvOrders") as GridView;
gvOrders.DataSource = GetData(string.Format("select top 10 * from Orders where RequestID='{0}'", requestId));
gvOrders.DataBind(); // this is the childGV
string cell_1_Value = gvCustomers.Rows[e.Row.RowIndex].Cells[0].Text;
string cell_2_Value = gvCustomers.Rows[e.Row.RowIndex].Cells[1].Text;
}
}
This is now working using:
foreach (GridViewRow gr in gvCustomers.Rows)
{
string requestStatus = gvCustomers.Rows[gr.RowIndex].Cells[3].Text;
}
But is there anyway to get the same value using the name of the column?
You could try the following:
if (e.Row.RowType == DataControlRowType.DataRow)
{
string requestId = gvCustomers.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvOrders = e.Row.FindControl("gvOrders") as GridView;
gvOrders.DataSource = GetData(string.Format("select top 10 * from Orders where RequestID='{0}'", requestId));
gvOrders.DataBind(); // this is the childGV
System.Data.DataRowView dr = (System.Data.DataRowView)e.Row.DataItem;
string requestStatus = dr["myColumnHeader"].ToString();
}
}
I want to mark checkboxlist item selected if it's value found in QueryString. e.g.
www.abcd.com/pproducts.aspx?price=1001-2000|2001-5000|5001-10000.
In this url I am filtering products with 3 different price range. Now I have checkboxlist which contains this prices like below
1001-2000
2001-5000
5001-10000
above-10000
so now I want to it should get selected 1001-2000, 2001-5000, 5001-10000
From below code I am redirecting page & making url
private void priceRange_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedPriceRange = priceRange.SelectedValue.ToString;
foreach (ListItem chk in priceRange.Items) {
if (selectedPriceRange.Contains(chk.Value)) {
chk.Selected = true;
}
}
Response.Redirect((Request.Url.AbsoluteUri) + "?price=" + selectedPriceRange);
}
string price = Request.QueryString["price"];
string[] priceList = price.Split('|');
foreach (string p in priceList)
{
if (chkList.Items.FindByText(p) != null)
{
chkList.Items.FindByText(p).Selected = true;
}
}
Above code will select each checkbox as per the value passed in query sting.
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 placed a gridview on my page and linked it to LinqDataSourceFemale (Female Table of Database) and i have a search event code like the below one
protected void ButtonSearch_Click(object sender, EventArgs e)
{
using(BerouDataContext Data = new BerouDataContext())
{
if (DropDownListGender.SelectedItem.Text == "Male")
{
int age = Convert.ToInt32(DropDownListAge.Text);
string education = DropDownListEducation.Text.ToString();
string maritalstatus = DropDownListMaritalStatus.Text.ToString();
//var religion = DropDownListReligion.Text.ToString();
string caste = DropDownListCaste.Text.ToString();
string city = DropDownListCity.ToString();
var SearchResultBoys = Data.Males.Where(tan =>
(tan.Age == age)
&& (tan.Education == education)
&& (tan.Group == maritalstatus)
&& (tan.Caste == caste));
GridViewMale.DataSourceID = "";
GridViewMale.DataSource = SearchResultBoys;
GridViewMale.DataBind();
}
else if (DropDownListGender.SelectedItem.Text == "Female")
{
int age = Convert.ToInt32(DropDownListAge.Text);
string education = DropDownListEducation.Text.ToString();
string maritalstatus = DropDownListMaritalStatus.Text.ToString();
//var religion = DropDownListReligion.Text.ToString();
string caste = DropDownListCaste.Text.ToString();
string city = DropDownListCity.ToString();
var SearchResultGirls = Data.Females.Where(tan =>
(tan.Age == age)
&& (tan.Education == education)
&& (tan.Group == maritalstatus)
&& (tan.Caste == caste));
GridViewFemale.DataSourceID = "";
GridViewFemale.DataSource = SearchResultGirls;
GridViewFemale.DataBind();
}
}
}
grid view doesnt appear after button click, please help me.
You have to persist the data in some fashion. It appears that after the button is clicked, a postback occurs and you lose it. One thing you might check on where the databinding fires, ensure that it is caught on subsequent postbacks.
Another thing you could do is simply store the data in a session variable, and upon postback re-bind the gridview with the data.
When the data is first retrieved, you could assign it to a session variable:
Session.Add("searchResultBoys", SearchResultBoys);
Session.Add("searchResultGirls", SearchResultGirls);
Then for example on subsuquent pageloads you could:
GridViewMale.DataSource = (DataTable)Session[searchResultBoys]; //be sure to cast whatever the datasource is, in my example I just used DataTable
GridViewFemale.DataSource = (DataTable)Session[searchResultGirls];
EDIT:
So in order to persist the data in a session variable, we have to save the var SearchResultBoys and SearchResultGirls into a type (in this case a datatable). Becuase saving the var in a session will just save the query expression and not the result set. Try converting your var SearchResultBoys and SearchResultGirls to this:
IEnumerable<DataRow> SearchResultsBoys = Data.Males.Where(tan =>
(tan.Age == age)
&& (tan.Education == education)
&& (tan.Group == maritalstatus)
&& (tan.Caste == caste));
Then what we can do is assign that result to a datatable - where it can be stored in memory) and persisted.
DataTable dt = SearchResultsBoys.CopyToDataTable<DataRow>();
Now you can bind the data as before:
GridViewMale.DataSourceID = "";
GridViewMale.DataSource = SearchResultBoys;
GridViewMale.DataBind();
Once that is working for you on the girls and boys data, then I can show you how to persist using a session or global variable.
Remove this GridViewFemale.DataSourceID = ""; line
And are you bind gridview in page load inside of !IsPostBack?
If it not bind,Please bind gridview in inside of !IsPostBack in pageload event
Edit
the coding for
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// here is Bind gridview code .
}
}