How to fire OnSelectedIndexChanged of GridView using c# code - c#

I have 2 grids, grid1 and grid2.
grid2 will be filled based on which row is clicked in grid1. I have done it by binding OnSelectedIndexChanged of grid1.
But at page load the grid2 will be empty as no row selection is made.
So I was planning of firing the row selection of grid1 using c# code so that both grids will be having data at page load.
I have started coding like.
grid1.DataSource = versions.DefaultView;
grid1.SelectedIndex = 0;
grid1.DataBind();
But the event is not firing.
Can anyone help me in solving this issue?

You can just call the method programmatically.
grid1.DataSource = versions.DefaultView;
grid1.SelectedIndex = 0;
grid1.DataBind();
grid1_SelectedIndexChanged(grid1, new EventArgs());

You don't need the event on Page_Load because you already know what the selected index of the first grid should be. The event is needed after user interaction with the page. Just DataBind() the second grid on Page_Load which data corresponding to the 0 selected index of the first grid the same way that you databind the first grid.
if (!IsPostBack)
{
grid1.DataSource = versions.DefaultView;
grid1.SelectedIndex = 0;
grid1.DataBind();
DataBindGridByIndex(0);
}
else
{
grid1.DataSource = versions.DefaultView;
grid1.DataBind();
}
public void DataBindGridByIndex(int index)
{
// Logic to databind second grid by selected index.
}

Related

How to keep values in textbox inside a binded GridView on ASP.NET?

I have a gridView, and inside is there exist a modifiable textbox.
I also have a dropdownlist, where if I click the dropdownlist, the system will read the database in SQL and display it in gridView.
How do I keep the number I previously typed in the first row of the gridView, when a new data is added after the dropdownlist is clicked?
Normally, the previously entered value of the textbox will be resetted if i rebind the gridView witthout refilling the textbox with a saved list or behaviour
Thank you very much in advance
I'm assuming you are using something like the OnSelectedIndexChanged event of the DropDownList. In there you can use FindControl to find the TextBox, store the data, rebind the GridView and set the value back to the TextBox. You need to use FindControl twice, one for the old and once for the new TextBox.
Note the use of oldValues.Count instead of GridView1.Rows.Count. If there were less rows in the new dataset than in the old you would get Index out of Bounds error.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
List<string> oldValues = new List<string>();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
TextBox tbOld = GridView1.Rows[i].FindControl("TextBox1") as TextBox;
oldValues.Add(tbOld.Text);
}
//rebind gridview here
for (int i = 0; i < oldValues.Count; i++)
{
TextBox tbNew = GridView1.Rows[i].FindControl("TextBox1") as TextBox;
tbNew.Text = oldValues[i];
}
}
You have used dropdownlist and textbox inside gridview?
if you click dropdownlist select value then postback to server and textbox value reset?

How to create button column in radgrid dynamically in asp.net?

How to create button column in radgrid dynamically in asp.net?
I have a radgrid in My Page. I want to create button column in radgrid dynamically. I create columns and set command name for them.When I click on one of item and go to ItemCommand event , command name is null (""). Why command name is empty?
I have a data table that contain 3 column.
all columns the first , dynamically generate.
private void createColumnToGrid(DataTable dtData)
{
radGridTicketByFlagList.DataSource = new string[] { };
radGridTicketByFlagList.Columns.Clear();
for (int i = 0; i < dtData.Columns.Count; i++)
{
GridButtonColumn col = new GridButtonColumn();
col.ButtonType = GridButtonColumnType.LinkButton;
col.CommandName = "Total";
col.UniqueName = "TCFlag" + i;
col.HeaderText = dtData.Columns[i].ToString();
col.DataTextField = dtData.Columns[i].ToString();
radGridTicketByFlagList.Columns.Add(col);
}
}
Then fill data source of radgrid.
private void FillRptTicketByFlagMonthList()
{
//........
radGridTicketByFlagList.DataSource = new string[] { };
DataTable dtTicketFlag= clsReportManager.GetRptTicketByFlag(); // fill data table
radGridTicketByFlagList.DataSource = dtTicketFlag;
radGridTicketByFlagList.DataBind();
}
grid is generated. When I click on a item in grid (link button) , and go to ItemCommand event, e.CommandName is empty. Why??
I want to When I click on item , do an action for me.
Some time ago i had same problem, then i used this tip from telerik forum:
http://www.telerik.com/forums/commandname-is-empty-if-the-column-if-created-from-code
so sum up, you need to add to your grid Rebind() after creating button column.
Maybe there is some other way to make it works, but i don't know them :(

GridView row values not changed after update

I want to update row in GridView with this code but after editing GridView not changes:
protected void res_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["dt"];
GridViewRow row =res.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["name"] = ((TextBox)(row.Cells[6].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["dewey"] = ((TextBox)(row.Cells[5].Controls[0])).Text;
*dt.Rows[row.DataItemIndex]["subject"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
Session["dt"] = dt;
res.EditIndex = -1;
res.DataSource = dt;
res.DataBind();
}
my Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt;
if (!IsPostBack)
{
dt= Converter.ListBooks(new classes.Book().GetAll());
Session["dt"] = dt;
res.DataSource = dt;
res.DataBind();
}
else
{
dt=(DataTable)Session["dt"];
res.DataSource = dt;
res.DataBind();
}
}
for example I changed line that have * to this:
dt.Rows[row.DataItemIndex]["subject"] = "tx";
and after edit "subject" column changed to "tx", so I don't know why ((TextBox)(row.Cells[4].Controls[0])).Text return TextBox's text before edit?
Because you're calling DataBind(); method each time page refreshed (POST or GET), let me explain more if user put the new value in the TextBox and click on update button to trigger res_RowUpdating even Page_Load will fire and bind the Gird with database values which is the old values and neglect the user input value.
I think, you just need to rebind the grid
Remove the else part in your page_load.
Should do it for you.
You are binding the Grid every time there is a postback which is not required.
Maybe changes are done but the form is not being updated.
Try putting gridview control inside an Update Panel Control and call UpdatePanel.Update().
When you work with a web control, what you see can be different from what actually is because changes in data are not autoupdated in the presentation layer.
To solve this "problem" you can make a postback (retrieving everything) of the whole page, but this is like killing a fly with a bazooka because you do not need everything, just what has been updated, so for this purpose there are several tool that allow you to make partial updates, for example the AJAX control: UpdatePanel.
Hope it helps.
Update: Call the AcceptChanges() method on the DataTable and erase the else branch on the Page_Load after if(!PostBack)
Call the AcceptChanges() method of the DataTable and then bind the GridView.

multiple ultragrids bound to the same datasource

I'm using ultraTextEditors to embed multiselect ultragrids. I set up the datasource in the form_load event. The facilities is a list.
ultraGrid1.DataSource = facilities;
ultraGrid2.DataSource = facilities;
The grid loads fine, but if I select rows in the first grid, the selected rows are set in the second grid. How do I disable this?
Also, I can't get selected row into the text editor from ultragrid2. I use AfterEditorButtonCloseUp event to do this. The first grid has the same code and it works fine. What am I missing here?
private void utxtExcludeReport_AfterEditorButtonCloseUp(object sender, Infragistics.Win.UltraWinEditors.EditorButtonEventArgs e)
{
if (ultraGrid2.Selected.Rows.Count == 0)
utxtExcludeReportLab.Text = string.Empty;
else if (ultraGrid2.Selected.Rows.Count == 1)
utxtExcludeReportLab.Text = ultraGrid2.Selected.Rows[0].Cells[0].Text;
else
utxtExcludeReportLab.Text = "<multiple>";
}
Before you set the datasource for the second ultragrid, you need to create a new BindingContext for it, otherwise events raised by the datasource will be propagated to both grids.
For example (off the top of my head, so it may need refining:
ultraGrid2.BindingContext = new BindingContext();
ultraGrid2.DataSource = facilities;

GridView paging inside an UpdatePanel or PlaceHolder components

I'm new to ASP.NET.
Im developing ASP.NET C# web form which creating GridView components dynamically and filling them using the data received from my webservice.
I'm creating these GridView components programmatically in server-side (cs file)- it has to be flexible - 1 GridView and sometimes 10 GridView components.
The problem occurs when I'm trying to add pagination - whenever the user clicks the "next" page, the whole page is getting refreshed because of a postBack and I'm loosing all my data and the page returns Blank/Empty.
I used PlaceHolder to hold the GridView components, while searching for a solution, I found UpdatePanel as a better alternative - as far as I understand the page can be partially refreshed - which means that only the UpdatePanel has to be refreshed...but it doesn't work.
The following code sample is my TEST, the UpdatePanel is the only component initiated in the client side (.aspx page), the rest initiated programmatically in .cs .
how can I solve the issue described above?
Why does the whole page is getting refreshed and I'm loosing my data?
can you recommend another way? can provide me with any code sample?
If I'm not rebuilding the GridView, it doesn't work...
Here is my Default.aspx.cs
public partial class TestAjaxForm : System.Web.UI.Page
{
DataTable table;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindGridView();
}
public void bindGridView()
{
GridView gridView1 = new GridView();
gridView1.AutoGenerateColumns = true;
gridView1.PageSize = 2;
gridView1.AllowPaging = true;
gridView1.PagerSettings.Mode = PagerButtons.Numeric;
gridView1.PagerSettings.Position = PagerPosition.Bottom;
gridView1.PagerSettings.PageButtonCount = 10;
gridView1.PageIndexChanging += new GridViewPageEventHandler(this.GridView1_PageIndexChanging);
table = new DataTable();
table.Columns.Add("FirstName");
table.Columns.Add("LastName");
DataRow row = table.NewRow();
row["FirstName"] = "John";
row["LastName"] = "Johnoson";
table.Rows.Add(row);
row = table.NewRow();
row["FirstName"] = "Johnny";
row["LastName"] = "Marley";
table.Rows.Add(row);
row = table.NewRow();
row["FirstName"] = "Kate";
row["LastName"] = "Li";
table.Rows.Add(row);
panel.ContentTemplateContainer.Controls.Add(gridView1);
gridView1.DataSource = table;
gridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gridView1 = (GridView)sender;
gridView1.PageIndex = e.NewPageIndex;
gridView1.DataSource = table;
gridView1.DataBind();
}
}
Thank you.
If you want a custom GridView approach to work, you have to recreate and rebind the grid on every page load... that's the problem with dynamic Grids... Dynamic controls don't retain their viewstate, but if you added the grid and dynamically generated the columns, that would work easier for you (because I think it may dynamically remember the columns, or you can set AutoGenerateColumns to true, and it brings in your data row column names).
HTH
You should create your GridView and add it to the control tree in the PreInit or Init event handler so that they have a chance to properly bind to ViewState, and it should be done whether or not there's a postback: if you don't add them in a postback, they obviously won't be there to display anything.
DataBinding can happen later in the page life cycle.
Paging only seems to work if you also use an ObjectDataSource; I've never been able to get it to work with a GridView by itself.
I think the easiest thing to do is have the gridview declared in the aspx page inside the place holder, while the place holder is also contained inside the update panel.
For what I can see, John is not doing anything that can't be declared in the markup itself so that shouldn't be a problem. If for some reason the gridview should not be displayed on the screen, it suffices to set the Visible property of the placeholder to false.
As far as paging is concerned, as RickNz correctly points out, it will only retain the state if you bind the gridview to either a LinqDatasource, SqlDatasource or ObjectDatasource but if you bind it to custom business objects, what you need to do is save the data in Session and rebind it again on PageIndexChanged.
In pseudo code, would be sometging like this.
Page_load
{
If (!IsPostBack)
Binddata();
}
private void Binddata()
{
var data = Getdata();
Gridview1.DataSource= data;
Gridview.DataBind();
Session["data"]=data; // cache the data
}
protected void Gridview1_indexchanged(object sender, GridviewPageEventArgs e)
{
var data= Session["data"];
Gridview1. DataSource=data;
Gridview1.DataBind();
GridView1.PageIndex=e.NewPageIndex;
}

Categories

Resources