Problem filling dropdown list of gridview from dataset - c#

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();
}

Related

show header and footer in gridview asp.net when data source return no data

Goal
show header and footer when Sqldatasource of GridView1 returns no data
Problem
now this is what i did so far i have a GridView in my asp.net application which shows meetings of a persons stored in database
in footer of GridView i added functionality of adding new meeting for person
but problem arise when a person don't have meetings stored in database data source bounded to gridview return no data and there goes my functionality of adding new meeting because GridView does not display until they have a row
any solution i can show header but how to show footer when GridView have no data
i dont want to use EmptyDataTemplate because i have to reimplement add new meeting functionality (if i am right)
thanks in advance
Here while binding datatable to gridview datasource , you can check number of rows and depend on row count you can set datasource to your gridview
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
bindGV();
}
}
public void bindGV() {
SqlDataAdapter dap = new SqlDataAdapter("YourSQlQuery ", cn);
DataSet ds = new DataSet();
dap.Fill(ds);
DataTable myDt = ds.Tables[0];
if (myDt.Rows.Count == 0)
{
myDt.Rows.Add(myDt.NewRow());
GridView1.DataSource = myDt;
GridView1.DataBind();
GridView1.Rows[0].Visible = false;
}
else
{
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
}

asp.net foreach row in dataset make a balloon with text

I got a question for you guys.
How do I Dynamicly add an item to asp.net?
there a way to make a balloon looking box of text?
I know how to get items into ds from database and fill it up and read it for each row there is. but that does not help me alot when I want to make dynamicly some stuff and get a ballon view of text just like if you are looking at your phone and see the text messeges thats how I want it to look like.
I took a example of my code where I show how I fill the dataset and how I bind the data into a Gridview
DBControl.cs
public DataSet GetData(String queryString)
{
DataSet ds = new DataSet();
try
{
//run the query.
SqlDataAdapter adapter = new SqlDataAdapter(queryString, m_helpdeskconnection);
// Fill the DataSet.
adapter.Fill(ds);
}
catch
{
// The connection failed. Display an error message.
//Message.Text = "Unable to connect to the database.";
}
return ds;
}
AdministrerBrugere.aspx.cs
DBControl db = new DBControl();
String queryString;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
queryString = "SELECT KundeNr, Navn FROM Kunder";
BindData();
}
}
private void BindData()
{
// Run the query and bind the resulting DataSet
// to the GridView control.
db.ConnOpenHelpdesk();
DataSet ds = db.GetData(queryString);
GridView1.DataSource = ds;
GridView1.DataBind();
db.ConnCloseHelpdesk();
}
You could use a DataRepeater to bind your content and use an ItemTemplate that has a CSS styled DIV to make it look like a baloon.
Try these links:
http://www.w3schools.com/css/css3_borders.asp
http://www.w3schools.com/aspnet/aspnet_repeater.asp

Bind a Gridview within a Gridview

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

Gridview not retaining old values in c# and ASP.Net

I have an ASP.Net gridview which is binding properly.On edit i am editing certain fields.then after i need to edit other rows as well.But when i am trying to edit other rows the previously edited rows get reset n retain their older values.
The requirement is as such that i have to edit many rows and the on a button click i need to push all the edit values to the database
You need to maintain your GridView's datasource between postbacks.
You can do this by storing your DataTable in Cache, Session, or any persistent storage.
Upon edit of a row, save the changes to this DataTable, then rebind the Gridview (from this DataTable).
When the user clicks "save all", you can save the changed rows of the DataTable to the database.
If you need to keep track of which rows have changed, you can maintain a list of PrimaryKeys that have changed in cache or Session.
Are you checking !IsPostBack inside Page_Load event before binding the grid? If you are not binding the grid in Page_Load event, please post the code to bind the grid.
The problem with your code is,you r binding grid on page load.. so when page is loading , it can bind the values which are in database. for that write bind method on Post back and also maintain your values on sessions or Hidden Fields,when you click on save button update database with that sessions or hidden fields..
morning bryan...here is that code for getting the value from the gridview to the datatable
private void getGridInfo()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("Select", typeof(byte)));
dt.Columns.Add(new System.Data.DataColumn("Client", typeof(string)));
dt.Columns.Add(new System.Data.DataColumn("PrincipleAmt", typeof(double)));
foreach (GridViewRow row in grdRepayment.Rows)
{
CheckBox Select = (CheckBox)row.FindControl("ChkSelect");
Label ClientName = (Label)row.FindControl("lblClientName");
Label Principal = (Label)row.FindControl("lblPricipal");
dr = dt.NewRow();
dr[0] = Convert.ToByte(Select.Checked);
dr[1] = ClientName.Text;
dr[2] = Convert.ToDouble(Principal.Text);
dt.Rows.Add(dr);
}
Session["TempTable"] = dt;
}
now here is the code for updating that session variable which holds the datatable,this must be done in RowUpdating Event of the Gridview.
protected void grdRepayment_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DataTable myDatatable;
GridViewRow row = grdRepayment.Rows[e.RowIndex];
grdRepayment.EditIndex = -1;
if (row != null)
{
myDatatable = (DataTable)Session["TempTable"];
for (int i = 0; i < myDatatable.Rows.Count; i++)
{
if (e.RowIndex == i)
{
myDatatable.Rows[i][1] = Convert.ToString(Client);
myDatatable.Rows[i][2] = Convert.ToString(Principal);
Session["TempTable"] = myDatatable;
grdRepayment.EditIndex = -1;
grdRepayment.DataSource = myDatatable;
grdRepayment.DataBind();
}
}
}
}
and make sure you bind the grid from this session variable only in RowEditing and RowCancellingEdit Events.
Once you are done with the Editing thing simply click the button which will push the edited content to the DATABASE...
Please check you'r gridview binding method was call page load and inside of !isPostBack?
for
Void page_load()
{
if(!IsPostBack)
{
//Call GridView Binding method
}
}
protected void grdRepayment_RowEditing(object sender, GridViewEditEventArgs e)
{
grdRepayment.EditIndex = e.NewEditIndex;
myDatatable = (DataTable)Session["TempTable"];
grdRepayment.DataSource = myDatatable;
grdRepayment.DataBind();
}
This is how we need to Bind the grid in RowEditing and RowCancelingEdit

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