Read data from SqlDataSource or GridView - asp.net

I have SqlDataSource and GridView on web form. GridView.DataSourceID = mySqlDataSource.
When I call myGridView.DataBind(), all data successfully bind on the page.
How is it possible to read already got data from mySqlDataSource or myGridView objects as DataTable or DataView? Thanks

The data in the gridview can read by using FindControl property of Gridview control. For example, for reading values set in the Checkbox column in the grid.
for (i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chk = (CheckBox)GridView1.Rows[i].FindControl("checkbox1");
//here code for using value captured in chk
}

Provided your data set isn't gigantic, you could store it in the Session, bind your GridView to the Session data, and then re-use the Session data in your other web objects.
Your code would then look something like this (you'll have to forgive any minor inaccuracies -- I'm away from my development box at the moment):
protected override OnInit(object sender, EventArgs e)
{
base.OnInit();
if (Page.IsPostback == false)
{
SetSessionData();
}
//
// Set your GridView, DataTable, DataView, etc. events here.
//
}
void SetSessionData();
{
List<YourDataBoundObject> myDataBoundObject = GetYourDataBoundObject(); // Or Collection<T>, IEnumerable<T>, etc.
Session["data"] = myDataBoundObject;
}
void YourGridView_Load(object sender, EventArgs e)
{
BindYourGridView();
}
void BindYourGridView()
{
YourGridView.DataSource = GetSessionData();
YourGridView.DataBind();
}
List<YourDataBoundObject> GetSessionData()
{
return (List<YourDataBoundObject>) Session["data"];
}
void YourDataTable_Load(object sender, EventArgs e)
{
BindYourDataTable();
}
void BindYourDataTable()
{
YourDataTable.DataSource = GetSessionData();
YourDataTable.DataBind();
}

Related

Custom Cell Appearance in GridView change event

I am disabling a checkbox column in a XtraGrid GridView with the following code (works as expected). Got the code from this post https://www.devexpress.com/Support/Center/Question/Details/Q423605:
private void GridViewWeeklyPlan_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
if (e.Column.FieldName == "Ignore")
{
CheckEditViewInfo viewInfo = ((GridCellInfo)e.Cell).ViewInfo as CheckEditViewInfo;
viewInfo.CheckInfo.State = DevExpress.Utils.Drawing.ObjectState.Disabled;
}
}
ISSUE
I want to enable the checkbox again when a certain column changes and has a value. This is where I am stuck and I thought I can change it in the GridView's CellValueChanged event, but I do not know how to reference the cell/column for the row:
private void GridViewWeeklyPlan_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
{
if (e.Column.FieldName != "Reason") return;
if (String.IsNullOrEmpty(e.Value.ToString()))
{
//Make sure the checkbox is disabled again
}
else
{
//Enable the checkbox to allow user to select it
}
}
You need to refresh a cell in the Ignore column. You can do this by calling the GridView.RefreshRowCell method. To identify a row that you need to refresh, the CellValueChanged event provides the e.RowHandle parameter.
private void GridViewWeeklyPlan_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
{
if (e.Column.FieldName != "Reason") return;
GridView view = (GridView)sender;
view.RefreshRowCell(e.RowHandle, view.Columns["Ignore"]);
}
The CustomDrawCell event will be raised again to update the cell appearance.

how to data bind to dropdownlist when checkbox is checked in asp.net

I have a project that using dropdownlist for choices.When check checkbox1 dropdown automatically bind data from database using table1 and when I check checkbox2 dropdown automatically binding data from database using table2.I do not want to use get data by using any button .How can I do that .Please help me.
here is code by using button:
public void LokasyonDoldur()
{
birimBUS = new BirimBUSV1();
List<BirimVO> birimVO = new List<BirimVO>();
DrpChcs.Items.Clear();
List<ListItem> items = new List<ListItem>();
birimVO = birimBUS.LokasyonlariGetir();
foreach (var item in birimVO)
{
items.Add(new ListItem(item.BirimAdi, item.ID.ToString()));
}
DrpChcs.Items.AddRange(items.ToArray());
}
public void BirimleriDoldur()
{
PoliklinikBUS poliklinikBUS = new PoliklinikBUS();
List<PoliklinikVO> poliklinikVO = new List<PoliklinikVO>();
DrpChcs.Items.Clear();
List<ListItem> items = new List<ListItem>();
poliklinikVO = poliklinikBUS.Poliklinikler();
foreach (var item in poliklinikVO)
{
items.Add(new ListItem(item.PoliklinikAdi, item.ID.ToString()));
}
DrpChcs.Items.AddRange(items.ToArray());
}
protected void BtnLokasyon_Click(object sender, EventArgs e)
{
if (ChckLctn.Checked == true && ChckBrm.Checked==false)
{
LokasyonDoldur();
}
else if (ChckLctn.Checked == false && ChckBrm.Checked == true)
{
BirimleriDoldur();
}
else
{
}
Button1.Visible = true;
BtnLokasyon.Visible = false;
}
protected void DrpChcs_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
KirilimId = Int32.Parse(DrpChcs.SelectedValue);
BPolikilinikID= KirilimId;
}
but I do not want to use this one.
ohh its another language. its hard to read. but what you basicly have to do is check which checkbox is checked in the page load and then load the dropdown based on what is loaded.
something like this. (I have typed it from my head so its not like copy-paste but you get the idea)
page_load
{
if(checkbox1.checked)
{
dropdown.dataitems = items1;
dropdown.databind();
return;
}
if(checkbox2.checked)
{
dropdown.dataitems = items2;
dropdown.databind();
return;
}
}
YOu can call the Button1_click event from the Dropdown list selected index changed event like this
Button1_Click(Button1,new EventArgs());
and in this you can hide that button from the page and in code behind you are calling the same function
OR
You can refactor the code in a seperate function from the button click event and call that function in the selected index changed event.
Please let me knwo if I misunderstood your question
Thanks

reatining selection of drodown list which is inside a user control

I have seen two few other posts related to this but I have doubts related to my code. So kindly bear with me.
I have user control which has a text boa and a drop down list and few custom validators.
The user control is added dynamically through a code.
I am using follwoing code to load the dropdownlist inside user control itself
protected void Page_Load(object sender, EventArgs e)
{
ddl_RRC.DataSource = dicRC_Desc;
ddl_RRC.DataTextField = "value";
ddl_RRC.DataValueField = "key";
ddl_RRC.DataBind();
txtRC.Text = Request.Form[txtRC.UniqueID]; //To retain the value of text box
}
I am adding the user control dynamically on Page_Init
protected void Page_Init(object sender, EventArgs e)
{
if (GetPostBackControl(this) == "btnNewRow")
{
custControlCountID++;
}
for (int i = 0; i < custControlCountID; i++)
{
RejRow customControl = (RejRow)LoadControl("~/RejRow.ascx");
customControl.ID = "rejRow" + i;
divHolder.Controls.Add(customControl);
}
}
Viewstate is enabled for both the text box and drop down list.
As I am using the same ID while adding the controls in Page_Init, why the controls are not getting the values from viewstate?
I think the only problem is that you have you're databinding the DropDownList on every postback from Page_Load. Just check the IsPostback-property, e.g.:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ddl_RRC.DataSource = dicRC_Desc;
ddl_RRC.DataTextField = "value";
ddl_RRC.DataValueField = "key";
ddl_RRC.DataBind();
}
txtRC.Text = Request.Form[txtRC.UniqueID]; //To retain the value of text box
}
However, i'm not sure why you need to set the TextBox.Text property from the form-fields since it should store it's Text also in ViewState.

Textbox value null when trying to access it

namespace Dynamic_Controls.Dropdowndynamic
{
public partial class DropdowndynamicUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (ControlCount != 0)
{
Recreatecontrols();
}
}
private void Recreatecontrols()
{
// createtextboxes(ControlCount);
createtextboxes(2);
}
protected void createtextboxes(int ControlCount)
{
DynPanel.Visible = true;
for (int i = 0; i <= ControlCount; i++)
{
TextBox tb = new TextBox();
tb.Width = 150;
tb.Height = 18;
tb.TextMode = TextBoxMode.SingleLine;
tb.ID = "TextBoxID" + this.DynPanel.Controls.Count;
tb.Text = "EnterTitle" + this.DynPanel.Controls.Count;
tb.Load+=new EventHandler(tb_Load);
tb.Visible = true;
tb.EnableViewState = true;
DynPanel.Controls.Add(tb);
DynPanel.Controls.Add(new LiteralControl("<br/>"));
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Int32 newControlCount = Int32.Parse(DropDownList1.SelectedValue);
//createtextboxes(newControlCount);
//ControlCount+=newControlCount;
createtextboxes(2);
}
protected void Button1_Click(object sender, EventArgs e)
{
readtextboxes();
}
public void readtextboxes()
{
string x = string.Empty;
for (int a = 0; a < DynPanel.Controls.Count; a++)
{
foreach (Control ctrl in DynPanel.Controls)
{
if (ctrl is TextBox)
{
x = ((TextBox)ctrl).Text;
}
x+=x+("\n");
}
Result.Text = x;
}
}
private Int32 ControlCount
{
get
{
if (ViewState["ControlCount"] == null)
{
ViewState["ControlCount"] = 0;
}
return (Int32)ViewState["ControlCount"];
}
set
{
// ViewState["ControlCount"] = value;
ViewState["ControlCount"] = 2;
}
}
private void tb_Load(object sender, EventArgs e)
{
LblInfo.Text = ((TextBox)sender).ID + "entered";
}
}
}
Are you adding these controls dynamically in Page_Load (by, I'm assuming, calling your AddRequiredControl() method)? If so, is it wrapped in a conditional which checks for IsPostBack? The likely culprit is that you're destructively re-populating the page with controls before you get to the button click handler, so all the controls would be present but empty (as in an initial load of the page).
Also, just a note, if you're storing each control in _txt in your loop, why not refer to that variable instead of re-casting on each line. The code in your loop seems to be doing a lot of work for little return.
You need to recreate any dynamically created controls on or before Page_Load or they won't contain postback data.
I'm not entirely clear what happens on DropdownList changed - are you trying to preserve anything that has been entered already based on the textboxes previously generated?
In any event (no pun intended) you need to recreate exactly the same textboxes in or before Page_Load that were there present on the postback, or there won't be data.
A typical way to do this is save something in ViewState that your code can use to figure out what to recreate - e.g. the previous value of the DropDownList. Override LoadViewState and call the creation code there in order to capture the needed value, create the textboxes, then in the DropDownList change event, remove any controls that may have been created in LoadViewState (after of course dealing with their data) and recreate them based on the new value.
edit - i can't figure out how your code works now, you have AddRequiredControl with parameters but you call it with none. Let's assume you have a function AddRequiredControls that creates all textboxes for a given DropDownList1 value, and has this signature:
void AddRequiredControls(int index)
Let's also assume you have a PlaceHolder called ControlsPlaceholder that will contain the textboxes. Here's some pseudocode:
override void LoadViewState(..) {
base.LoadViewState(..);
if (ViewState["oldDropDownIndex"]!=null) {
AddRequiredControls((int)ViewState["oldDropDownIndex"]);
}
}
override OnLoad(EventArgs e)
{
// process data from textboxes
}
void DropDownList1_SelectedIndexChanged(..) {
ControlsPlaceholder.Controls.Clear();
AddRequiredControls(DropDownList1.SelectedIndex);
ViewState["oldDropDownIndex"]=DropDownList1.SelectedIndex;
}

How can I prevent the LinqDataSource Where clause from resetting on postback?

I'm trying to set the where clause on a LinqDataSource object bound to a GridView programmatically on a button click, but when the GridView rebinds data (for instance, when the user sorts) the Where clause resets back to the empty string. Is there a way to prevent this, or is there a better way to filter my results?
Perhaps you just add a ViewState property into your page/user control and then retrieve it on all post back?
public string MyLinqSourceWhere
{
get { return (string)this.ViewState["MyLinqSourceWhere"]; }
set { this.ViewState["MyLinqSourceWhere"] = value; }
}
public void Page_Load(object sender, EventArgs e)
{
this.myLinqSource.Where = this.MyLinqSourceWhere;
}
public void Button1_Click(object sender, EventArgs e)
{
this.MyLinqSourceWhere = " .... ";
this.myLinqSource.Where = this.MyLinqSourceWhere;
}
If that doesn't work, then perhaps bind on the LinqDataSource.Selecting event the fetch property from the viewstate to your where clause?? It all depends

Resources