How to get values from Gridview column - asp.net

I have an editable GridView that emails it's content to all companies. The first row of the Gridview contains the company name (just 1 name per row). I want to email the Gridview to a specific email address based off of the company name in the first row. e.g - if first row equals companyname1 then send the email to company one; if first row equal company two, then send the email to company two. I attempted the following:
//C# - code snippet behind button
foreach (GridView item in gvCompanies.Rows)
{
if (item.SelectedRow.Cells[1].Text == "company1")
{
txtEmailAddresses.Text = "company1#gmail.com";
}
else if (item.SelectedRow.Cells[1].Text == "company2")
{
txtEmailAddresses.Text = "company2.com";
}
else if (item.SelectedRow.Cells[1].Text == "company3")
{
txtEmailAddresses.Text = "company3#aol.com";
}
else if (item.SelectedRow.Cells[1].Text == "company4")
{
txtEmailAddresses.Text = "company#aol.com";
}
}
...Could anyone provide some guidance as to what am doing wrong here?

Try Something like this...
protected void gvCompanies_SelectedIndexChanged(object sender, EventArgs e)
{
//for (int i = 0; i < gvCompanies.Rows.Count; i++)
// {
if (gvCompanies.SelectedIndex == i)
{
String compName = gvCompanies.Rows[i].Cells[1].Text; //Gets the data cell value from the grid to string
if(compName == "company1")
{
txtEmailAddresses.Text = "company1#gmail.com";
}
else if(compName == "company2")
{
txtEmailAddresses.Text = "company2#gmail.com";
}
........and so on
}
// }
}
You need to set the folowing 2 properties of gridview.
1] AutoGenerateSelectButton="true" and
2] onselectedindexchanged="GridView1_SelectedIndexChanged".

Related

How to get the position(col, row) of the user changed cell in a Table control?

I'm using tutorial_Form_Table.
The table has dynamically assigned values, something like:
for (col = 1; col <= 5; col++)
{
for (row = 1; row <= 5; row++)
{
if ((col == 2) || (col == 4))
{
if (row > 1)
table.cell(col,row).data(row*col);
else
table.cell(col,row).data("Text "+int2str(row*col));
}
else
table.cell(col,row).data("Text "+int2str(row*col));
}
}
I need to get the position of the cell when I enter new value in it, so I can update the corresponding table with the value entered.
Thank you.
Table has two properties: row() and column() which return values of current active cell.
public void activeCellChanged()
{
super();
info(strFmt('%1 %2 %3', Table.row(), Table.column(), Table.cell(Table.column(), Table.row()).data()));
}
On each of the controls you add to the table control you can override the modified method to see the new value you entered.
public boolean modified()
{
boolean ret;
ret = super();
info(strFmt('New data that we need to save: %1, %2 -> %3', Table.row(), Table.column(), Table.cell(Table.column(), Table.row()).data()));
return ret;
}
If you are working with a lot of data you should consider using some other control such as .NET grid control because of performance issues.

Getting gridview data in variables and inserting it to database

I am making a shopping cart type of thing using grid view user will keep adding item in it after doing it so user will click save i want to get values from all columns of grid view each row at a time and save it to database.
here is the code for grid view load
protected void add_Click(object sender, EventArgs e)
{
product.Item = Item_Drop.SelectedItem.Text;
product.Quantity = quantity_box.Text;
int qun =Convert.ToInt32(quantity_box.Text);
int unitP= Convert.ToInt32(unitPrice_box.Text);
product.item_Toal = (qun*unitP).ToString();
list.Add(product);
temp_gridView.DataSource = list;
temp_gridView.DataBind();
}
And here is what i am trying to get values
public void Values_from_grid()
{
foreach(temp_gridView row in temp_gridView.Rows)
{
for(int i = 0; i < temp_gridView.Columns.Count, i++)
{
String header = temp_gridView.Columns[i].HeaderText;
String cellText = row.Cells[i].Text;
}
}
}
i am not getting any values in "header" or "cellText" . .. .
Use this code to get header row value .
GridViewName.HeaderRow.Cells[0].Text;
Found Answer no need to use
GridView.Rows.Count
just use a simple int to iterate
int i = 0;
foreach(GridViewRow row in temp_gridView.Rows)
{
box.Item_id = temp_gridView.Rows[i].Cells[0].Text;
box.Quantity = temp_gridView.Rows[i].Cells[1].Text;
box.Total = temp_gridView.Rows[i].Cells[2].Text;
i++;
}

How to persist search criteria and results of a c# .NET application page

Scenario:
User submits search criteria and selects an item from search results on the same page, which navigates to a new page of details for the selected item.
When the User returns to the search screen, the search criteria & results (including selected page and sort-order) should be preserved from their last visit.
Related information:
All form submissions are POSTs.
Navigation back to the search screen may not be available from last browser history (e.g. more than one details screen may be encountered, or the user may navigate directly to the search screen from an alternative menu.)
Search results are provided using Telerik RadGrid control.
I'm looking for a generic solution that will be able to be applied to different search screens.
In some instances, the item may be DELETED from within the details screen, and should therefore not appear in the search results when the screen is next encountered.
Thoughts:
I've read a lot of suggested methods for addressing various parts of this scenario, but I'm still confused; no comprehensively "correct" solution jumps to the forefront.
I guess I'm asking for recommendations/approach rather than a whole solution spelled out for me (although that would be nice! ;-)
The .NET VIEWSTATE would seem to do exactly what I'm after (with the exception of #5) - Is there some way of leveraging off this so that viewstate can be used between pages, and not just between postbacks to the same page? (e.g. can I store/restore viewstate to/from a session variable or something? I haven't seen this suggested anywhere and I'm wondering if there's a reason why.)
Thanks in advance.
Thanks for all the advice.
For the benefit of others, here is a solution to this issue (no doubt there's room for improvement, but this works satisfactorily for the moment).
4 functions...
StoreSearchCookie - Persist the state/values of a panel of search criteria and a results grid in a cookie with a specified UID.
RestoreSearchCookie_Criteria - Read the cookie and re-populate the search criteira
RestoreSearchCookie_Results - Read the cookie and restore the grid state.
FindFormControls - Helper method to recursively find form-input controls in a container (pinched & modified from elsewhere on Stack Overflow)
NB...
I haven't addressed the multiple-tabs issue because our application doesn't allow them anyway.
RestoreSearchResults utilises GridSettingsPersister.cs available from Telerik website, (but I had to modify it to store the page number as well)
Usage is as follows...
protected void Page_PreRender(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
// Store the state of the page
StoreSearchCookie("SomeSearchPage", pnlSearchCriteria, gridResults);
}
else
{
// Restore search criteria
RestoreSearchCookie_Criteria("SomeSearchPage");
// Re-invoke the search here
DoSearch(); // (for example)
// Restore the grid state
RestoreSearchCookie_Results("SomeSearchPage");
}
}
Code follows...
protected void StoreSearchCookie(string cookieName, Panel SearchPanel, RadGrid ResultsGrid)
{
try
{
HttpCookie cookieCriteria = new HttpCookie("StoredSearchCriteria_" + cookieName);
// 1. Store the search criteria
//
List<Control> controls = new List<Control>();
FindFormControls(controls, SearchPanel);
foreach (Control control in controls)
{
string id = control.ID;
string parentId = control.Parent.ID;
string uid = string.Format("{0}>{1}", parentId, id);
string value = "";
Type type = control.GetType();
bool isValidType = true; // Optimistic!
if (type == typeof(TextBox))
{
value = ((TextBox)control).Text;
}
else if (type == typeof(DropDownList))
{
value = ((DropDownList)control).SelectedValue;
}
else if (type == typeof(HiddenField))
{
value = ((HiddenField)control).Value;
}
else if (type == typeof(RadioButton))
{
value = ((RadioButton)control).Checked.ToString();
}
else if (type == typeof(CheckBox))
{
value = ((CheckBox)control).Checked.ToString();
}
else
{
isValidType = false;
}
if (isValidType)
{
cookieCriteria.Values[uid] = value;
}
}
cookieCriteria.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(cookieCriteria);
// 2. Persist the grid settings
//
GridSettingsPersister SavePersister = new GridSettingsPersister(ResultsGrid);
HttpCookie cookieResults = new HttpCookie("StoredSearchResults_" + cookieName);
cookieResults.Values["GridId"] = ResultsGrid.ID;
cookieResults.Values["GridSettings"] = SavePersister.SaveSettings();
cookieResults.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(cookieResults);
}
catch (Exception exception)
{
Logger.Write(exception);
}
}
protected void RestoreSearchCookie_Criteria(string cookieName)
{
try
{
HttpCookie cookieCriteria = Request.Cookies["StoredSearchCriteria_" + cookieName];
if (cookieCriteria != null)
{
foreach (string key in cookieCriteria.Values.AllKeys)
{
string value = cookieCriteria[key];
string[] ids = key.Split('>');
string parentId = ids[0];
string id = ids[1];
Control control = FindControl(parentId).FindControl(id);
Type type = control.GetType();
if (type == typeof(TextBox))
{
((TextBox)control).Text = value;
}
else if (type == typeof(DropDownList))
{
((DropDownList)control).SelectByValue(value);
}
else if (type == typeof(HiddenField))
{
((HiddenField)control).Value = value;
}
else if (type == typeof(RadioButton))
{
((RadioButton)control).Checked = Boolean.Parse(value);
}
else if (type == typeof(CheckBox))
{
((CheckBox)control).Checked = Boolean.Parse(value);
}
}
}
}
catch (Exception exception)
{
Logger.Write(exception);
}
}
protected void RestoreSearchCookie_Results(string cookieName)
{
try
{
HttpCookie cookieResults = Request.Cookies["StoredSearchResults_" + cookieName];
if (cookieResults != null)
{
string gridId = cookieResults.Values["GridId"];
string settings = cookieResults.Values["GridSettings"];
RadGrid grid = (RadGrid)FindControl(gridId);
GridSettingsPersister LoadPersister = new GridSettingsPersister(grid);
LoadPersister.LoadSettings(settings);
grid.Rebind();
}
}
catch (Exception exception)
{
Logger.Write(exception);
}
}
private void FindFormControls(List<Control> foundSofar, Control parent)
{
List<Type> types = new List<Type> { typeof(TextBox), typeof(DropDownList), typeof(RadioButton), typeof(CheckBox), typeof(HiddenField) };
foreach (Control control in parent.Controls)
{
if (types.Any(item => item == control.GetType()))
{
foundSofar.Add(control);
}
if (control.Controls.Count > 0)
{
this.FindFormControls(foundSofar, control); // Use recursion to find all descendants.
}
}
}

ASPxComboBox Filtering Large DataSet Using XpoDataSource (DevExpress)

I tried to Filter an ASPxComboBox that gets data using an XpoDataSource, note that restoring and filtering data from a small data set works fine , the issue start when I try to filter large dataset - about 70000 records- from datasource the ComboBox loading becomes very slow since XpoDataSource gets all data from database table .
So I created a criteria for the XpoDataSource to reduce number of records restored ,then the ComboBox Keeps repeating the top 10 records while scrolling down the ComboBox, I don't know where the problem is.
I realized that what I need is similar to the example in the following link
But using an XpoDataSource instead of SqlDataSource1 .
I don't know how to write a similar code for an XpoDataSource .
this is my code :
protected void cmbServices_OnItemRequestedByValue_SQL(object source, DevExpress.Web.ASPxEditors.ListEditItemRequestedByValueEventArgs e)
{
try
{
string criteria = "";
if (string.IsNullOrEmpty(e.Value.ToString()) || e.Value.ToString().Length < 3)
{
criteria = "1 = 2";
}
else
{
criteria =
string.Format("(( Code like '{0}%' OR ProductName like '{0}%') AND CustomerId = {1})", e.Value.ToString(), (cmbServicesActivities != null && cmbServicesActivities.Value != null) ? cmbServicesActivities.Value.ToString() : "0");
}
dsServices.Session = LookupsSession;
dsServices.Criteria = criteria;
cmbServicesDescription.DataSource = dsServices;
cmbServicesDescription.DataBind();
}
catch (Exception exc)
{
Debug.WriteLine(exc.Message);
}
}
The Following Example demonstrates the answer of my question
public partial class _Default : System.Web.UI.Page {
Session session = XpoHelper.GetNewSession();
protected void cmb_ItemRequestedByValue(object source, DevExpress.Web.ASPxEditors.ListEditItemRequestedByValueEventArgs e) {
MyObject obj = session.GetObjectByKey<MyObject>(e.Value);
if (obj != null) {
cmb.DataSource = new MyObject[] { obj };
cmb.DataBindItems();
}
}
protected void cmb_ItemsRequestedByFilterCondition(object source, DevExpress.Web.ASPxEditors.ListEditItemsRequestedByFilterConditionEventArgs e) {
XPCollection<MyObject> collection = new XPCollection<MyObject>(session);
collection.SkipReturnedObjects = e.BeginIndex;
collection.TopReturnedObjects = e.EndIndex - e.BeginIndex + 1;
collection.Criteria = new BinaryOperator("Title", String.Format("%{0}%", e.Filter), BinaryOperatorType.Like);
collection.Sorting.Add(new SortProperty("Oid", DevExpress.Xpo.DB.SortingDirection.Ascending));
cmb.DataSource = collection;
cmb.DataBindItems();
}

Find if selected Checkboxes in repeater is of which gender

I have a repeater where I have a column with checkboxes and one column with gender which i populate with database value.
I want to find out if user has selected multiple checkboxes of same gender e.g. male if so do something otherwise If a user selects multiple checkboxes with a mixture of male and female then do something else.
so far I was thinking to add this to a list and then see if list has same values but not sure if it is best idea here is my code (I have a hidden field to get gender ), I am running this on click event of a button:
foreach (RepeaterItem rptItem in myrepeater.Items)
{
hiddenGender = rptItem.FindControl("hiddenGender") as HiddenField;
if (Convert.ToInt32(hiddenGender.Value) == 0)
{
gender.Add(0);
}
else if (Convert.ToInt32(hiddenGender.Value) == 1)
{
gender.Add(1);
}
else if (Convert.ToInt32(hiddenGender.Value) == 2)
{
gender.Add(2);
}
}
ps without usage of linq as it is framework 2.0
I'm not sure if i understand what you want to do, but if i do, this code does the same:
foreach (RepeaterItem rptItem in myrepeater.Items)
{
hiddenGender = rptItem.FindControl("hiddenGender") as HiddenField;
gender.Add(Convert.ToInt32(hiddenGender.Value));
}
got it, here is the code to maybe help others(first I get the first item and see if it matches next item) :
public static bool ListEquality(IEnumerable<int> lstGender)
{
int? first = null;
bool isUnique = true;
foreach (var item in lstGender)
{
if (first == null)
{
first = item;
}
else if (first.Value != item)
{
isUnique = false;
}
}
return isUnique;
}

Resources