I have a Rad Grid that I bind a data source to in the Page Load. I am trying to then capture the row that is selected when the user clicks a row. I have successfully done this with a Rad Grid that has a data source set in the markup. Is it possible to do this with a grid with a dynamically set data source.
Markup
<telerik:RadGrid ID="rgTable" runat="server" OnSelectedIndexChanged="rgTable_OnSelectedIndexChanged">
<ClientSettings EnableRowHoverStyle="true" EnablePostBackOnRowClick="true">
<Selecting AllowRowSelect="true" />
</ClientSettings>
</telerik:RadGrid>
C#
protected void Page_Load(object sender, EventArgs e)
{
int id = Convert.ToInt32(Request.QueryString["ID"]);
ConnString = Connections.Search(0, 999999, null, null, null, id, null, null, null, null, null)[0].Connection_String;
StoreTableAndViewNames();//This method sets arrTables with ArrayList
rgTable.DataSource = arrTables;
rgTable.DataBind();
}
protected void rgTable_OnSelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (rgTable.SelectedItems.Count > 0)//This test is failing
{
GridDataItem item = (GridDataItem)rgTable.SelectedItems[0];
string table = item.Cells[0].ToString();
StoreColumnNames(table);
rgColumn.DataSource = arrColumns;
rgColumn.DataBind();
}
}
catch (Exception ex)
{
errorlbl.Text = ex.ToString();
}
}
In your code, Data is bind to rgTable on ever page load.
As the result, when a row is selected at client side, data is bind torgTable again before OnSelectedIndexChanged is fired.
The quick fixes is not to bind rgTable on post back.
protected void Page_Load(object sender, EventArgs e)
{
....
if (!IsPostBack)
{
rgTable.DataSource = arrTables;
rgTable.DataBind();
}
}
However, preferred method is to use NeedDataSource event
If you bind data in NeedDataSource event, RadGrid knows when & where to look for data if it is needed.
protected void rgTable_OnNeedDataSource(object sender,
GridNeedDataSourceEventArgs e)
{
rgTable.DataSource = arrTables;
}
Related
I have a drop down list which will load up with a series of customer ID numbers. I then have a gridview control on my page with the select hyperlink. When i click on the link to select the row in gridview i would like my dropdown to change to that number.
Below is what i have tried but doesn't work:
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (!GridView1.SelectedIndex.Equals(-1))
{
DropDownList ddl;
ddl = (DropDownList)form1.FindControl("ddl_Customers");
ddl.SelectedValue = (String)GridView1.SelectedDataKey.Values[0];
}
}
Handle the SelectedIndexChanged event for GridView1
void GridView1_SelectedIndexChanged(Object sender, EventArgs e) {
ddl_Customers.SelectedValue = GridView1.SelectedDataKey.Value.ToString();
}
You can directly use GridView1.SelectedValue.ToString() for this. To use that, you should define a datakeyname like this: <asp:Gridview DataKeyNames="CustomerID">
Then all you need is this:
void GridView1_SelectedIndexChanged(Object sender, EventArgs e) {
ddl_Customers.SelectedValue = GridView1.SelectedValue.ToString();
}
I'm trying to take a GridView and get back the data from the row that was clicked. I've tried the code below and when I click the row I get back the selected index but when I look at the actual rows in the GridView they show empty. Not sure what I am missing.
.ASP make my grid.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True"
CssClass="datatables" Width="100%"
DataSourceID="SqlDataSource1"
GridLines="None" ShowFooter="True" AllowSorting="True"
onrowcreated="GridView1_RowCreated"
onrowdatabound="GridView1_RowDataBound" ShowHeaderWhenEmpty="True"
onrowcommand="GridView1_RowCommand"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<HeaderStyle CssClass="hdrow" />
<RowStyle CssClass="datarow" />
<PagerStyle CssClass="cssPager" />
</asp:GridView>
On each row data bound I make sure that the click should set the selected index.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex);
}
}
Then when the selected index changes by clicking this gets fired which I can put a breakpoint on the first line and I see the index of what I clicked on get stored in a. However when I get to the foreach it skips right past it because it shows GridView1 having a Count of 0 rows. In theory it should have a couple hundred rows and when the index matches it should grab the data in the 6th cell over and store it in string b. Why am I getting no rows on the click?
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int a = GridView1.SelectedIndex
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowIndex == a)
{
b = row.Cells[6].Text;
}
}
}
Here is my page load.
protected void Page_Load(object sender, EventArgs e)
{
c = HttpContext.Current.Session["c"].ToString();
SqlDataSource1.ConnectionString = //My secret
string strSelect = "SELECT columnnames from tablenames where c in (#c)
SqlDataSource1.SelectParameters.Clear();
SqlDataSource1.SelectCommand = strSelect;
SqlDataSource1.SelectParameters.Add("c", c);
try
{
GridView1.DataBind();
}
catch (Exception e)
{
}
GridView1.AutoGenerateColumns = true;
}
Try just grabbing the row from the SelectedRow property:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string b = row.Cells[6].Text;
}
It's my understanding that the Rows collection doesn't get repopulated on PostBacks when you're using those data source controls (like SqlDataSource).
You could probably use your existing code if you called .DataBind() on your GridView prior to trying to iterate through the Rows:
GridView1.DataSourceID="SqlDataSource1";
GridView1.DataBind();
But that seems a little hacky.
After seeing your Page_Load, I see that you need to wrap your databinding code in an if(!Page.IsPostBack) block. Databinding on every postback is interrupting the process of ASP.NET maintaining the state of your controls via the ViewState.
I have a drop down which has the list of delegates. When the user selects a delegate then I populate the available meet-timings in the second dropdown using the selectedindexchange event of the 1st dropdown
Aspx page
<asp:DropDownList ID="delegate_ddl" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddldelegates_SelectedIndexChanged" Width="200px"></asp:DropDownList>
<asp:DropDownList ID="delegatetime_ddl" runat="server" Width="90px"></asp:DropDownList>
<asp:Button ID="adddelegate" runat="server" Text="Add" onclick="adddelegate_Click"/>
.cs page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds1 = getdata.getdelegatelist();
delegate_ddl.DataSource = ds1.Tables[0];
delegate_ddl.DataTextField = "DELEGATE_NAME";
delegate_ddl.DataValueField = "DELEGATE_ID";
delegate_ddl.DataBind();
delegate_ddl.Items.Insert(0, "--Select--");
}
}
protected void ddldelegates_SelectedIndexChanged(object sender, EventArgs e)
{
string delselection = delegate_ddl.SelectedValue.ToString();
DataSet ds2 = getdata.getdelegatetimelist(delselection);
if (ds2.Tables[0].Rows.Count > 0)
{
delegatetime_ddl.DataSource = ds2.Tables[0];
delegatetime_ddl.DataTextField = "TIMESLOT";
delegatetime_ddl.DataValueField = "TIMEID";
delegatetime_ddl.DataBind();
}
else
{
time_lbl.Text = "No slots Open";
}
}
protected void adddelegate_Click(object sender, EventArgs e)
{
string delegateselected = delegate_ddl.SelectedValue.ToString();
string timeslotselected = delegatetime_ddl.SelectedValue.ToString();
getdata.delegatemeetinsert(personidd, delegateselected, timeslotselected);
}
Now the data gets inserted – but my question here is
As soon as the user click add button I would like to display the delegate selected and the time slot selected in a some sort of a grid view or dynamic table below with a delete option.
Can someone please provide a code sample in C# to achieve the above
Instead of using Gridview for displaying data use some basic control like Labels,it will reduce lot's of unncessary code. use Asp.net 'Panel' control and encapsulate all label and button(for delete purpose) into Panel then hide/show according to need. here is the outline of code that might help you,
if(!page.IsPostBack) // This goes into Page_Load
{
Panel1.Visible=false;
}
protected void adddelegate_Click(object sender, EventArgs e) // add this additional code
{
Panel.Visible=True;
GetDelegate()// This method retrieve the delegate you inserted..
Lable1.Text= "Set here Delegate name you just Retrieved"
Label2.Text="Delegate time you retrived"
}
protected void BtnRemovedelegate_Click(object sender, EventArgs e)
{
string Personidd= retrieve person id
string delegateName= Lable1.text;
String timeslot=Label2.Text
SomeDeleteMethod(personidd, delegateName, timeslot);
Panel1.Visible=false;
}
Hope you get the idea..
I have a RadGrid in my ASP.Net app and I have set the AllowPaging to True and PageSize to 10, now it load 10 items per RadGridPage which is what I wanted, but as soon as I press Next Page button (Arrow look button) nothing loads and RadGrid gets empty.
How can I make it work normal?
protected void Page_Load(object sender, EventArgs e)
{
PopulateGridOnLoad();
}
private void PopulateGridOnLoad()
{
rgCustomers.DataSource = odsCustomers;
// your datasource type
rgCustomers.MasterTableView.VirtualItemCount = 28;
//your datasource type total/count
rgCustomers.CurrentPageIndex = rgCustomers.MasterTableView.CurrentPageIndex;
rgCustomers.Rebind();
}
protected void grdName_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
rgCustomers.DataSource = odsCustomers;
// your datasource type
rgCustomers.MasterTableView.VirtualItemCount = 28;
//your datasource type total/count
rgCustomers.CurrentPageIndex = rgCustomers.MasterTableView.CurrentPageIndex;
//Donot rebind here
}
protected void btnLoad_Click(object sender, EventArgs e)
{
odsCustomers.SelectParameters["CustomerFullName"].DefaultValue = txtFullName.Text;
odsCustomers.SelectParameters["CustomerMelliCode"].DefaultValue = txtMelliCode.Text;
odsCustomers.SelectParameters["CustomerHomeAddress"].DefaultValue = txtHomeAddressPart.Text;
odsCustomers.SelectParameters["CustomerWorkAddress"].DefaultValue = txtWorkAddressPart.Text;
rgCustomers.DataSource = odsCustomers;
rgCustomers.DataBind();
}
You will have to set up following attributes of the grid in design
<telerik:RadGrid ID="grdName"
AllowPaging="True"
AllowCustomPaging="True"
VirtualItemCount="0" PageSize="15" >
Populate grid on load vb.net
Private Sub PopulateGridOnLoad()
grdName.DataSource = source ' your datasource type
grdName.MasterTableView.VirtualItemCount = source.Total 'your datasource type total/count
grdName.CurrentPageIndex = grdName.MasterTableView.CurrentPageIndex
grdName.Rebind()
End Sub
Populate grid on load c#.net
private void PopulateGridOnLoad()
{
grdName.DataSource = source;
// your datasource type
grdName.MasterTableView.VirtualItemCount = source.Total;
//your datasource type total/count
grdName.CurrentPageIndex = grdName.MasterTableView.CurrentPageIndex;
grdName.Rebind();
}
Override NeedDatasource vb.net
Protected Sub grdName_NeedDataSource(sender As Object, e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles grdName.NeedDataSource
grdName.DataSource = source ' your datasource type
grdName.MasterTableView.VirtualItemCount = source.Total 'your datasource type total/count
grdName.CurrentPageIndex = grdName.MasterTableView.CurrentPageIndex
'Donot rebind here
End Sub
Override NeedDatasource c#
protected void grdName_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
grdName.DataSource = source;
// your datasource type
grdName.MasterTableView.VirtualItemCount = source.Total;
//your datasource type total/count
grdName.CurrentPageIndex = grdName.MasterTableView.CurrentPageIndex;
//Donot rebind here
}
After a long time I found the solution, the problem involved 2 minor issues :
1.I had both DataSource (in code) and DataSourceID (property) set and they didn't work together well
2.I had both AllowPaging and AllowCustomPaging set to true, when they are both true neither works :) that's the telerik team you know, but they are great I was kidding
You need to define the "onNeedDataSource" radgrid event where you shoud reset the datasource of your grid.
protected void RadGrid_NeedDataSource(object sender, EventArgs e)
{
IsNeedDataSource = true;
}
and than in page OnPreRender event you shoul do smth like:
protected override void OnPreRender(object sender, EventArgs e)
{
DriverLinksGrid.DataSource = value;
DriverLinksGrid.DataBind();
}
I'm not shure, maybe you can bind data right in OnNeedDataSource event. But the DataBind() method may be not not available from there.
I have a datagridview which is loaded through a strored procedure. It has an ID column which i want to hide it but still access its value. I set the dataKeyNames and i have a method
protected void grdTime_OnDataBound(object sender,EventArgs e)
{
grdTime.Columns[1].Visible = false;
}
which i am trying to hide this column but i get the following error. If i remove the line inside the method it works. Here is the error.
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Try this code in the method and then check..
grdTime.Columns[0].Visible = false;
hide the column in Row_Created event
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].CssClass = "hiddencol";
//e.Row.Cells[2].CssClass = "hiddencol";
}
else if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[1].CssClass = "hiddencol";
//e.Row.Cells[2].CssClass = "hiddencol";
}
}
here hiddencol is a css class
.hiddencol
{
display:none;
}
in the above code i'm hiding second column of my grid
If you've set GridView's AutoGenerateColumns to true(default), the Columns-Collection is empty. Following should work then:
1.)
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false;
}
2.)
foreach (TableRow row in GridView1.Controls[0].Controls)
{
row.Cells[0].Visible = false;
}
you can use like this in gridview tag on .aspx page
<Columns>
<asp:BoundField HeaderText="Merchandise Id" DataField="MerchandiseId" Visible="false" /></columns>