gridview databinding problem - c#

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.

Related

Refresh GridView After Data is Deleted From DetailView Using C#

When user select any record from the GridView then my DetailView is updated based on the selection of the GridView. So what I am trying to do is that when I delete anything from the DetailView then I want to refresh the GridView so basically I don’t want to show still the deleted record in the GridView. I have tried to resolve this issue by doing the data bind after my connection and SQL statement but it does not refresh it. One thing to note is that I am using a Accordion pane but both my gridview and the detailview are on the same pane. I am not sure if this is breaking anything. Here is my code:
protected void Refresh_ItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName.Equals("Delete", StringComparison.CurrentCultureIgnoreCase))
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("select ID, Name, Address from dbo.MyTable", con);
DataTable dt = new DataTable();
da.Fill(dt);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
}
You may use the event of the Data view called "ItemDeleted" as follows:
DetailViewName_ItemDeleted(object sender,
DetailsViewDeletedEventArgs e)
{
// Refresh the GridView control after a new record is updated
// in the DetailsView control.
GridViewName.DataBind();
}
The above code is from the official MSDN site for detail view control.
The other way (which I prefer) is to handle the data grid during the Page_load procedure so when you press your delete button in the detail view, the page will perform a postback.
So in the procedure Page_load you can call another procedure which fills the data grid. The code might be like this:
if (isPostback)
{
FillGrid();
}
private void FillGrid()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("select ID, Name, Address from dbo.MyTable", con);
DataTable dt = new DataTable();
da.Fill(dt);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
Your code doesn't show anything where the record is actually deleted so it's understandable that when you re-fetch the data still contains everything.
What you need to do is:
Execute a sql statement to delete the record
Re-fetch the data
Rebind the data.
If you follow those 3 steps it will work.
try to use the event that is called in case of pressing the delete key from the DGV
private void DGV_DeleteKeyPressed(object sender, KeyEventArgs e)
{
//enter code here
}

ASP.NET why Gridview Paging on page 2 and the rest of it are disappear?

I have so many list of ServerName in GridView, so I decide to add paging. The data show list result on page 1 but on page 2 and the rest of it is not display anything. I already have OnPageIndexChanging="GridViewServer_PageIndexChanging" in GridViewServer property. Please help! Here is c# code behind,
protected void GridViewServer_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridViewServer.PageIndex = e.NewPageIndex;
GridViewServer.DataBind();
}
A GridView binding function codes,
public void BindGridView()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Database_Shared_NotebookConnectionString"].ConnectionString);
conn.Open();
string sqlquery = ("SELECT * FROM tblServer");
SqlCommand command = new SqlCommand(sqlquery, conn);
SqlDataAdapter adp = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adp.Fill(ds);
GridViewServer.DataSource = ds.Tables[0];
GridViewServer.DataBind();
}
You need to set your GridView's datasource appropriately. You can't just call DataBind if the datasource isn't properly set. Basically what it amounts to is binding your GridView to null (which would have no page 2). I would recommend having a private method that is responsible for this process and whenever you need to bind you call that.
private void BindGridViewServer()
{
GridViewServer.DataSource = GetYourData(); // This should get the data
GridViewServer.DataBind();
}
Call this method from within your event with:
protected void GridViewServer_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridViewServer.PageIndex = e.NewPageIndex;
BindGridViewServer();
}
This could be made more extensible by passing in the GridView as a parameter, but you'd have to have other parameters as well to make sure the method retrieves the proper data.
Here's a very good tutorial (with sample code) on custom GridView paging. This makes the paging controls look like the familiar ones you see on a lot of search engines, forums, etc.
http://geekswithblogs.net/aghausman/archive/2009/05/18/custom-paging-in-grid-view.aspx
You have to give datasource to GridViewServer every time on page index changed.
so the code would be like this
protected void GridViewServer_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridViewServer.PageIndex = e.NewPageIndex;
GridViewServer.Datasource = MethodReturningDataTable();
GridViewServer.DataBind();
}

updating asp.net grid view

I'm using asp.net grid view.
I call some sql-server stored procedure and
attach it to the gridView:
gvResults.DataSource = dr;
gvResults.DataBind();
I want to make a specific column editable.
How do i attach the update sp to the view?
You can use the UpdateCommand
http://msdn.microsoft.com/en-us/library/ms972948.aspx
Try a handler for Rowdatabound for the gridview:
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
HyperLink hlControl = new HyperLink();
hlControl.Text = "Info";
hlControl.NavigateUrl = e.Row.Cells[3].Text;
e.Row.Cells[3].Controls.Add(hlControl);
}
catch
{
}
}
I wrote this to change the response from datasource in specific column to be changed to hyperlink control, you can do anything you want with the column.

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

create gridview dynamically

when i click Add button i need to create gridview dynamically, where the gridview has to contain Textbox,DatePicker and dropdownlist.where as the values entered in each row of the gridview have to store it in database and retrive.
To get you started, an object is generally created dynamically in C# like this:
DataGridView g = new DataGridView();
The rest of the stuff you're asking - the textbox, datepicker, dropdownlist columns and reading/writing to the database - is quite involved and can't be answered here in any simple way.
You can just Bind the GridView onClick of Add Button
Like this
protected void btnADD_Click(object sender, EventArgs e)
{
objENT = new ENT();//using n-tier Architecture
objENT.ProcType = "ProcedureType";
DataSet ds = BLL.ProcessGrid(objENT);
GridviewDisplay.DataSource = ds;
GridviewDisplay.DataBind();//GridviewBind
}
I have used stored Procedure here,You can use any other methods as u wish

Categories

Resources