I am attempting to bind a GridView to a DataSet, but it throws a Stack overflow error. When I debug it, it runs to the DataBind line just fine (it seems like its getting the right records from the server and everything), but after executing the DataBind, it jumps to the top of the method and reruns the entire method, which results in an stack overflow.
I can't understand why this isn't working. I've done something very similar with a DataTable before and it worked fine.
Here is how I'm binding
public void CreateGrid(String str)
{
try
{
sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["MY_CONNECTION_STRING"].ConnectionString;
sqlConnection.Open();
DataSet dt = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(str, sqlConnection);
adapter.Fill(dt);
sqlConnection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name + ":" + ex.Message);
}
if (dt.Tables.Count > 0)
{
Grid.DataSource = dt;
Grid.DataBind();
}
}
And here is my HTML part
<asp:GridView runat="server" ID="Grid" AutoGenerateColumns="false"
OnDataBinding="RebindGrid" AllowPaging="True" PageSize="10" AllowSorting="True" CellPadding="5"
OnPageIndexChanging="Grid_PageIndexChanging"
OnSorting="Grid_Sorting"
Width="100%" CssClass="mGrid">
<Columns>
<asp:BoundField DataField="ID" ItemStyle-Width="0%"
HeaderText="" Visible="false" SortExpression="ID"/>
</Columns>
</asp:GridView>
This looks like a problem
OnDataBinding="RebindGrid"
Every time data is bound, you rebind. We would have to see the code for RebindGrid.
It depends on what the RebindGrid method actually does but it looks like your rebinding your grid as your binding it.
Remove OnDataBinding="RebindGrid".
Related
I want to be able to delete a row when I click on the delete button on that gridview. I have the aspx page and the code behind as well as the app code. The DeletePaymentCondition runs the store procedure to delete the row. But somehow the overall code doesnt work
aspx
<asp:GridView ID="gridview1" runat="server" HorizontalAlign="left" AutoGenerateColumns="false" CssClass="table table-bordered " GridLines="None"
AllowSorting="True" OnRowDeleting="OnRowDeleting">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="left" HeaderText="Payment Condition" HeaderStyle-CssClass="OGColor" HeaderStyle-ForeColor="white" SortExpression="monthToQuarters">
<ItemTemplate>
<span style="font-size:12px; color: #2980b9; text-align:left">
<asp:Label ID="lblUserId" runat="server" Visible="true" Text="<%# bind('payConditionId')%>"/>
</span>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150"/>
</Columns>
</asp:GridView>
cs
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lblEmpID = (Label)gridPayment.Rows[e.RowIndex].FindControl("lblUserId"); //This is Table Id load on Label1
int id = Convert.ToInt32(lblEmpID.Text.ToString());
dsPayment = objcommission.Delete(id);
gridPayment.DataSource = dsPayment.Tables[0];
gridPayment.DataBind();
}
app code
public DataSet DeletePayment(int id)
{
DataSet dsGetAllPayment;
dsGetAllPaymentCondition = SqlHelper.ExecuteDataset(OGconnection, CommandType.Text, "Delete FROM tblPay where pay ='" + id + "'");
return dsGetAllPayment;
}
You shoul execute two different SQL, one for the delete and a new select one to retreive the new data.
The DELETE should be executed using in a NonQuery because it does not return rows (only the number of rows affected).
public DataSet DeletePaymentCondition(int ids)
{
int rowsAffected = SqlHelper.ExecuteNonQuery(OGconnection, CommandType.Text, "Delete FROM [Accounting].[dbo].[tblPayConditions] where payConditionId ='" + ids + "'");
DataSet dsGetAllPaymentCondition = SqlHelper.ExecuteDataSet(OGconnection, CommandType.Text, "Select * FROM [Accounting].[dbo].[tblPayConditions]");
return dsGetAllPaymentCondition;
}
As a good praxys, you should consider changing it into parametrized queries. In this case it is safe because of the integer conversion, but in similar code with string parameters you would be prone to SQL Injection attacks
I got the solution. I've made changes to the cs file and as well as the code provided by bradbury9.
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(gridPaymentCondition.DataKeys[e.RowIndex].Value.ToString());
dsPaymentCondition = objcommission.DeletePaymentCondition(index);
gridPaymentCondition.DataSource = dsPaymentCondition.Tables[0];
updatePaymentConditionsWithoutRefresh();
}
I am calling the server and returning a datatable of results but when I try to bind to the gridview, it is throwing an error about not being able to find a field or property on the data source. I'm newer to gridviews and .NET controls so any help would be appreciated.
The GridView
<asp:GridView ID="gv_Search" AutoGenerateColumns="false" runat="server" AllowSorting="true" OnSorting="gv_Search_Sorting">
<Columns>
<asp:HyperLinkField NavigateUrl="#" Text="View"/>
<asp:BoundField SortExpression="Hdefendant_name" HeaderText="Name" DataField="Hdefendant_name"/>
<asp:BoundField SortExpression="Hdefendant_location" HeaderText="Location" DataField="Hdefendant_location"/>
<asp:BoundField SortExpression="Hdate" HeaderText="Date Entered" DataField="Hdate"/>
</Columns>
</asp:GridView>
The Code-Behind for Gridview page
(resultsList is a DataTable type)
var resultsList = defendantRepository.Search(start, end, name, location);
if (Defendant.hasRecords)
{
ViewState["PreliminaryInjunctions"] = resultsList.Columns;
gv_Search.DataSource = resultsList.Columns;
gv_Search.DataBind();
}
The Search (populates a DataTable and returns it to the variable resultsList from above)
dv is a DefaultView and
ds is a DataSet
using (var da = new SqlDataAdapter())
{
da.SelectCommand = cmd;
da.Fill(ds, "PreliminaryInjunctions");
}
dv = ds.Tables[0].DefaultView;
dt = dv.ToTable();
return dt;
The issue is I believe that you are binding the GridView to the Data Table's Columns property:
gv_Search.DataSource = resultsList.Columns;
gv_Search.DataBind();
That property is of type DataColumnCollection which does not contain names matching those defined in the BoundField elements, and hence the error.
Instead bind to the DataTable itself:
gv_Search.DataSource = resultsList;
gv_Search.DataBind();
Dear Stack Overflowers,
I have a gridview in the front end page and here it is in asp.net code:
<asp:GridView ID="grdManufact" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4"
GridLines="Horizontal" AllowPaging="True" OnRowDataBound="manufGridView_RowDataBound" EnableModelValidation="False" EnableSortingAndPagingCallbacks="True" HorizontalAlign="Center" OnSelectedIndexChanged="grdManufact_SelectedIndexChanged" OnPageIndexChanging="grdManufact_PageIndexChanging">
<Columns>
<asp:BoundField DataField="SrNo" HeaderText="SrNo" />
<asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="isModerated" HeaderText="Approved" />
<asp:BoundField />
Well that is the main part of it but it displays correctly and binds correctly upon page load.
Whenever I change page to page 2 or 3 or whatever of the gridview, my gridview disappears! I have tried putting a breakpoint in the PageIndexChanging function but the breakpoint is not reached which tells me that the event is not even firing and yet the gridview just disappears. Here is my backend function Page Index Changing anyway:
protected void grdManufact_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdManufact.PageIndex = e.NewPageIndex;
BindGrid();
}
And the BindGrid() function used to bind the grid :
public void BindGrid()
{
string strConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString();
SqlConnection conn = new SqlConnection(strConnectionString); // Connect to database
conn.Open(); // Open Connection
string com = "select ManufacturerID as SrNo, ManufacturerName as Manufacturer, ManufacturerDescription as Description,isModerated From VehicleManufacturer";
SqlDataAdapter adpt = new SqlDataAdapter(com, conn); // Select all manufacturers in the table
DataTable dt = new DataTable(); // Create a new Data Table
adpt.Fill(dt); // Fill it with manufacturers
grdManufact.DataSource = dt; // Make the datasource of the manufacturer grid the new table
grdManufact.DataBind(); // Bind data for the grid
conn.Close(); // Close database connection. Disconnect
}
Here is my page load in case you wanted that too:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // If this is the first time loading the page through postback
BindGrid(); // Bind the Manufacturers to the gridview
else
{
ClientScript.GetPostBackEventReference(this, string.Empty);
if (Request.Form["__EVENTTARGET"] == "Button2_Click")
{
//call the method
btnDelete_Click(this, new EventArgs());
}
}
}
Can you please tell me what I am doing wrong or point me in the right direction to fix this please?
remove EnableSortingAndPagingCallbacks="True" property if you need to excute server side page index changed event or set it false
I remember that this happen if you set EnableViewState = false. Make it EnableViewState = true ! If the grid disappears on every postback just put the binding in if(!IsPostBack) in Page_Load method.
I have a stored procedure in SQL that searches employee details. When it finds something,it returns and displays the data in a gridview. But how can I handle if it did not return anything? like when 'no record is found'?
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBReader"].ConnectionString))
{
using (SqlCommand com = new SqlCommand("[Reader].[usp_SearchUser]", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("#empID", SqlDbType.Int).Value = this.EmpID;
con.Open();
int result = com.ExecuteNonQuery();
if (result == 0)
{
this.NoRecord = "No Record Found";
}
else
{
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
search.DataSource = ds;
search.DataBind();
}
}
}
Did not get what is your exact question? do you want the gridview property when there is no data then it will show as no records found i.e. EmptyDataText="No records Found"
e.g.
<asp:GridView ID="GridView1" runat="server" EmptyDataText="No records Found">
<Columns>
<asp:boundfield datafield="empID" headertext="Employee ID"/>
<asp:boundfield datafield="empName" headertext="Employee Name"/>
</Columns>
</asp:GridView>
I suppose you use a webcontrol GridView? So you might use the GridView.EmptyDataTemplate to have full control of what to render if no data has been bound.
<asp:gridview id="yourGridView" runat="server">
<emptydatatemplate>
No Data Found!
<img src="noData.jpg"/>
</emptydatatemplate>
</asp:gridview>
Or just use EmptyDataText Property if you just want to show a text Message
<asp:gridview id="yourGridView" emptydatatext="No Data Found" runat="server">
....
</asp:gridview>
I am unable to guess the issue here , as the event of grid item command is not executing .I also changes the pageevent validation state but of no use.
I am pasting .aspx code as well as
The grid is binded perfectly
<telerik:RadGrid ID="frds" runat="server" OnItemCommand="go_frd" AutoGenerateColumns="false" >
<MasterTableView>
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:Button ID="bt" runat="server" CommandArgument='<%#Eval("frd_ID") %>' Text="test" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
The event is this
protected void go_frd(object o, GridCommandEventArgs e)
{
if (e.CommandName == "frd_go")
{
Response.Redirect("Profiling.aspx?uid=" + e.CommandArgument);
}
if (e.CommandName == "add_frd")
{
db_accessDataContext db = new db_accessDataContext();
Frd_request req = new Frd_request();
db.AddFriend(Int64.Parse(cur_mem_id), Int64.Parse(e.CommandArgument.ToString()));
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("dbo.addFriend", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(#"memID", Int64.Parse(cur_mem_id));
cmd.Parameters.Add(#"frdID", Int64.Parse(e.CommandArgument.ToString()));
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex) { }
}
}
I tried many approaches but unable to fire the event for button in grid
I checked it by putting a break point as well ,the trouble is it don't even start execution of the event
Binding COde
string query = "my query containing the frd_id ,works fine in query builder and it also is shown grid view ";
try { SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
adapter.Fill(d0); con.Close();
} catch (Exception ex) { }
frds.DataSource = d0;
frds.DataBind();
You need to set the CommandName:
<asp:Button ID="bt" runat="server"
CommandName="frd_go"
CommandArgument='<%#Eval("frd_ID") %>' Text="test" />
I had a similar issue today.
In my radgrid I had the code to build the sql and populate the radgrid in the page_load event, but I forgot to add
if (!IsPostBack) { }
around this code, so on every page load the grid was being rebuilt and the onitemcommand method was not working. The page seemed to be was posting back on button click or rowclick, but the event was just not firing. Try adding the if (!isPostback) code around your databinding and you might find it works for you.
You will need to set EnablePostBackOnRowClick property to true for ClientSettings. However this will cause a full post back.
.
.
.
</MasterTableView>
<ClientSettings EnablePostBackOnRowClick="true">
</ClientSettings>
</telerik:RadGrid>
You may want to check this thread on Telerik forums