Bind a Gridview within a Gridview - c#

I have GridView2 within another GridView1. I'm trying to populate it with the below code.
GridView4 is a gridview I was using to test that is not nested within another gridview. It populates with no problems.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow gvr in GridView1.Rows)
{
string connectionString = "Data Source=MyConnection String";
using (SqlConnection test = new SqlConnection(connectionString))
{
test.Open();
SqlCommand cmd = new SqlCommand("SELECT [ID], [CTNum], [PRPNum], [DateEntered], [CurrentRFBDate], [CurrentRFBPRPDate], [CurrentRFPDate], [CurrentRFPPRPDate], [EnteredBy] FROM [PRPDateTracking]", test);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
GridView4.DataSource = reader;
GridView4.DataBind();
((GridView)gvr.FindControl("GridView2")).DataSource = reader;
((GridView)gvr.FindControl("GridView2")).DataBind();
}
}
}
}

If each row of parent gridview is associated with nested GridView then You can find the nested gridview in RowDataBound event like this
GridView gvr = (GridView)e.Row.FindControl("GridView2")

You should find the inner (child)gridview in the RowDataBound event of the parent grid view and bind values to the child gridview.
refer these links to get an good idea about nested grids
http://www.codeproject.com/Articles/685079/Nested-GridView-in-ASP-NET-using-Csharp

Related

Add selected rows from one GridView to another GridView

I need to add the selected rows from one GridView to another GridView in ASP.NET C#.
So the code i was implemented on my project to copy selected rows from one Grid to another Grid.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=x;Integrated Security=True");
sc.Open();
SqlDataAdapter sd = new SqlDataAdapter("select * from BookDetails", sc);
DataSet ds = new DataSet();
sd.Fill(ds, "BookDetails");
sc.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
GridView2.DataSource = row; //error here
GridView2.DataBind();
}
when i run the project i got an error (GridView2.DataSource = row;) :-
"Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource."
Image of what i need to implement
error of the code
Have you tried typecasting "row" to be "IListSource, IEnumerable, or IDataSource."? If that doesnt work, it may be because GridView2.DataSource can only be IListSource, IEnumerable, or IDataSource thus meaning it simply isn't possible. I don't fully understand what you're trying to do in the function "GridView1_SelectedIndexChanged1".

ASPxGridView DeleteRow not deleting on another control callback

I'm using the DEVExpress's gridview and have this code that deletes the selected gridview row from another control's customcallback,
the line
GridFrom.DeleteRow(int.Parse(rowKey[2]));
retrieves the correct visibleIndex but does not remove the row from the gridview. The databind also does not refreshes the gridview's data and it requires refreshing of the page for the data to update
protected void ASPxTreeList1_CustomCallback(object sender, DevExpress.Web.ASPxTreeList.TreeListCustomCallbackEventArgs e)
{
string[] rowKey = e.Argument.Split('|');
string strConnectionString = ConfigurationManager.ConnectionStrings["dbname"].ConnectionString;
using (SqlConnection conn = new SqlConnection(strConnectionString))
{
string query = "DELETE FROM Table WHERE id=#id";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#id", rowKey[0]);
cmd.ExecuteNonQuery();
conn.Close();
}
}
GridFrom.DeleteRow(int.Parse(rowKey[2])); //rowKey[2] is the visibleIndex
GridFrom.DataBind();
}
}
it requires refreshing of the page for the data to update
You don't see grid changes, because ONLY ASPxTreeList is updated during ITS OWN callback.
As a possible solution, disable ASPxTreeList's callbacks or delete a grid row using the grid's CustomCallback instead (in a similar manner).
<dx:ASPxTreeList ID="ASPxTreeList1" runat="server" EnableCallbacks="false">
</dx:ASPxTreeList>
Check the The concept of callbacks - Why is it impossible to update external control data during a callback to another control learning guide regarding this.

edit/delete table data without gridview

I am new at asp.net and I have to do a research publications app. I have a table which displays data from database. I don't want to use gridview because i need to display table as in template and because I want to edit abstract of an article and I cant display all abstract in table (because abstract may be big). What I want to do is when click "delete" icon that I have in my table to delete all information of that specific row and when click "edit" icon to go to another page which has a form filled with data that get from database for that specific row and perform a simple update. In php i know how to do it by id but here I dont kno how to select a row and get the id.
This is code what i tried :
public partial class Edit_Delete : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
//open connection with database
connection.Open();
//query to select all users with the given username
command.CommandText = "select * from artikulli";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
using (SqlDataReader rd = command.ExecuteReader())
{
if (rd.HasRows)
{
while (rd.Read())
{
sb.Append("<tr>");
sb.Append("<td>");
sb.Append(rd[1].ToString());
sb.Append("</td>");
sb.Append("<td>");
sb.Append(rd[3].ToString());
sb.Append("</td>");
sb.Append("<td>");
sb.Append("<input type='image' src='images/icn_edit.png' title='Edit'>");
sb.Append(" <input type='image' src='images/icn_trash.png' title='Trash'>");
sb.Append("</td>");
sb.Append("</tr>");
}
}
}
Row1.InnerHtml = sb.ToString();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void ButtonDelete_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
//open connection with database
connection.Open();
//query to select all users with the given username
command.CommandText = "delete from artikulli ";
}
}
}
}
Instead of creating table in code, use DataList or Repease ASP.NET controls.
Here you can specify your own design template, and can bind event handlers to handle your edit and delete button/linkButton/imageButton events
For more information see:
Displaying Data with the DataList and Repeater Controls (VB)
Displaying Data with the DataList and Repeater Controls
How to use DataList control in ASP.NET using C#

Problem filling dropdown list of gridview from dataset

I'm using the code below:
protected void grdViewCInfo_RowDataBound(object sender, GridViewRowEventArgs e)
{
MySqlConnection objMycon1 = new MySqlConnection(strProvider);
objMycon1.Open();
MySqlCommand cmd1 = new MySqlCommand("select * from tblcountrynames",objMycon1);
MySqlDataAdapter da = new MySqlDataAdapter(cmd1);
DataSet ds = new DataSet();
da.Fill(ds);
// DropDownList Control Object Created to bind the data dynamically with each
// nested DropDownlist control placed inside the template column of the GridView
// Control.
DropDownList drdList;
// foreach loop is used to loop through each row of GridView Control.
foreach (GridViewRow grdRow in grdViewCInfo.Rows)
{
// Nested DropDownList Control reference is passed to the DrdList object.
// This will allow you access the properties of dropdownlist placed
// inside the GridView Template column.
drdList = (DropDownList)(grdViewCInfo.Rows[grdRow.RowIndex].FindControl("ddlCountry" ));
// DataBinding of nested DropDownList Control for each row of GridView Control.
drdList.DataSource = ds;
drdList.DataValueField = "ID";
drdList.DataTextField = "Name";
drdList.DataBind();
}
}
It gives an error as:
Object reference not set to an instance of an object.
At the line drdList.DataSource = ds;
How do I fix this???
Try specifying the COLUMN in the following line of code:
drdList = (DropDownList)( grdViewCInfo.Rows[ grdRow.RowIndex ][ColumnIndex].FindControl( "ddlCountry" ));
Another option is to loop through columns in another foreach
More info based on your comment:
Looks like you're new to ASP.NET, that's why I recommend the following:
Use asp:TemplateColumn and put the asp:DropDownList in the EditTemplate. Hook the DropDown up to SqlDataSource (or whatever else datasource you want to use).
The binding will be handled for you.
I can't elaborate any further w/o seeing your ASP.NET code and knowing more about your requirements.
Try This
DropDownList ddl;
int i = 0;
foreach (GridViewRow grdrow in grdmenu.Rows)
{
ddl = (DropDownList)grdmenu.Rows[grdrow.RowIndex].FindControl("ddloffer");
ddl.SelectedIndex = Convert.ToInt16(ds.Tables[0].Rows[i]["Offer"]);
ddl = (DropDownList)grdmenu.Rows[grdrow.RowIndex].FindControl("ddloffers");
ddl.SelectedIndex = Convert.ToInt16(ds.Tables[0].Rows[i]["OfferType"]);
i++;
ddl.DataBind();
}

gridview databinding problem

i am using asp.net with c#
and i want to bind my data to the gridview
i have success fully done that by wizard
but now it is show me this error
protected void Button1_Click(object sender, EventArgs e)
{
SqlDataAdapter dbadapter = null;
DataSet dbdata = new DataSet();
using (SqlConnection dbconn = new SqlConnection("Server=CJ\\SQLEXPRESS;Database=elligiblity;User ID=sa;Password=123;Trusted_Connection=False;"))
{
dbadapter = new SqlDataAdapter("select * from Main_Table", dbconn);
dbadapter.Fill(dbdata);
}
GridView1.DataSource = dbdata;
GridView1.DataBind();
}
i am getting this error
Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition
You cannot specify custom binding from code if gridview is already binded to a datasource. Either remove DataSourceID in gridview properties from your aspx page or change the select command of the sql datasource to which it is binded from code like,
protected void Button1_Click(object sender, EventArgs e)
{
sdsFtrtDet.SelectParameters.Clear(); // Clear any innitial parameters of your sql datasource which is binded with gridview
sdsFtrtDet.SelectCommand = "select * from tableA"; //Specify new query
sdsFtrtDet.DataBind(); // Data Bind
}
Cheers.
Edit
You probably are not seeing your gridview because you would have used template fields binded with datasource ? You can use another gridview to bind with your 2nd query. Leave the 1st gridview as it is so you wont get in trouble with template fields.
Cheers.
So that means that in your markup, you're specifying a value for DataSourceID, but then in the code you've shown, you're setting DataSource. DataSourceID and DataSource are mutually exclusive.

Categories

Resources