Gridview control in C#.net

Hi ,

I am getting error (Object reference not set to an instance of an object.) while trying to update and delete the datas in gridview control. This is the code which i have writen . could anyone assist me on this.

 

 

public partial class custom : System.Web.UI.Page

{

public string connectionstr = System.Configuration.ConfigurationManager.AppSettings["ptcon"];

MySqlConnection conn;

MySqlCommand cmd = new MySqlCommand();

DataSet ds = new DataSet();

MySqlDataAdapter da = new MySqlDataAdapter();protected void binddata()

{

conn =
new MySqlConnection(connectionstr);

cmd.Connection = conn;

conn.Open();

cmd.CommandText =
"select * from categorytable";da = new MySqlDataAdapter(cmd);

da.Fill(ds);

cmd.ExecuteNonQuery();

GridView1.DataSource = ds;

GridView1.DataBind();

conn.Close();

 

}

protected void Page_Load(object sender, EventArgs e)

{

if (!Page.IsPostBack)

{

binddata();

}

}

protected void butadd_Click(object sender, EventArgs e)

{

conn =
new MySqlConnection(connectionstr);

cmd.Connection = conn;

conn.Open();

cmd.CommandText =
"insert into categorytable values('" + txtcatid.Text + "','" + txtcatname.Text + "','" + txtcatcolor.Text + "')";

cmd.ExecuteNonQuery();

GridView1.DataSource = ds;

binddata();

conn.Close();

}

protected void Gridview_delete(object sender, GridViewDeleteEventArgs e)

{

GridView1.DataSource = ds;

ds.Tables[0].Rows[GridView1.Rows[e.RowIndex].DataItemIndex].Delete();

cmd.ExecuteNonQuery();

GridView1.DataSource=ds;

conn.Close();

binddata();

 

 

}

 

protected void gridview_update(object sender, GridViewUpdateEventArgs e)

{

int i=e.RowIndex;

string catid=(GridView1.Rows[e.RowIndex].FindControl("txtcatid") as TextBox).Text;

string catname=(GridView1.Rows[e.RowIndex].FindControl("txtcatname") as TextBox).Text;string catcolor=(GridView1.Rows[e.RowIndex].FindControl("txtcatcolor") as TextBox).Text;

GridView1.EditIndex=-1;

binddata();

ds=(
DataSet)GridView1.DataSource;

ds.Tables[0].Rows[i]["CategoryID"]=catid;

ds.Tables[0].Rows[i]["CategoryName"]=catname;ds.Tables[0].Rows[i]["CategoryColor"]=catcolor;

GridView1.DataSource=ds;

binddata();

conn.Close();

 

}

 

protected void Gridview_cancel(object sender, GridViewCancelEditEventArgs e)

{

GridView1.EditIndex = -1;

binddata();

}

protected void Gridview_edit(object sender, GridViewEditEventArgs e)

{

GridView1.EditIndex = e.NewEditIndex;

binddata();

}

protected void GridView1_PageIndexChanged(object sender, GridViewPageEventArgs e)

{

 

GridView1.PageIndex = e.NewPageIndex;

binddata();

}

}

 HTML code:

<body>

<form id="form1" runat="server">

<div>

&nbsp;&nbsp;

<asp:Label ID="lblcategoryid" runat="server" Text="CategoryID"></asp:Label>

<asp:TextBox ID="txtcatid" runat="server"></asp:TextBox>

<asp:Label ID="Label2" runat="server" Text="CategoryName"></asp:Label>

<asp:TextBox ID="txtcatname" runat="server"></asp:TextBox>

<asp:Label ID="Label3" runat="server" Text="CategoryColor"></asp:Label>

&nbsp;

<asp:TextBox ID="txtcatcolor" runat="server"></asp:TextBox><br />

<br />

<br />

<asp:Button ID="butadd" runat="server" OnClick="butadd_Click" Text="Add" /><br />

<br />

<br />

 

<asp:GridView ID="GridView1" runat="server" Width="258px" AutoGenerateColumns="False" OnRowCancelingEdit="Gridview_cancel" OnRowDeleting="Gridview_delete" OnRowEditing="Gridview_edit" OnRowUpdating="gridview_update" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanged">

<Columns>

<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />

<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />

<asp:BoundField DataField="CategoryColor" HeaderText="CategoryColor" />

<asp:CommandField HeaderText="Edit" ShowEditButton="True" />

<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />

</Columns>

</asp:GridView>

<br />

<br />

<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>

<br />

<br />

</div>

</form>

</body>

Thanks,

Anitha

 

 

0
anishanmugam
8/27/2008 4:50:01 AM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

1 Replies
789 Views

Similar Articles

[PageSpeed] 14

Hi anishanmugam ,

I think there is some problem with the way that you retrieve the datasource .

For example:

anishanmugam:
protected void gridview_update(object sender, GridViewUpdateEventArgs e)

{

int i=e.RowIndex;

string catid=(GridView1.Rows[e.RowIndex].FindControl("txtcatid") as TextBox).Text;

string catname=(GridView1.Rows[e.RowIndex].FindControl("txtcatname") as TextBox).Text;string catcolor=(GridView1.Rows[e.RowIndex].FindControl("txtcatcolor") as TextBox).Text;

GridView1.EditIndex=-1;

binddata();

ds=(
DataSet)GridView1.DataSource;

ds.Tables[0].Rows[i]["CategoryID"]=catid;

ds.Tables[0].Rows[i]["CategoryName"]=catname;ds.Tables[0].Rows[i]["CategoryColor"]=catcolor;

GridView1.DataSource=ds;

binddata();

conn.Close();

 

}

That is wrong way. WebFrom app is very diffrent from WinForm app. GridView control does not preserver it's datasource when postback happens.

You can see my sample here to see how to use Session to implement this function : http://forums.asp.net/t/1310440.aspx

 

 



Samu Zhang
Microsoft Online Community Support

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question.
0
Samu
8/29/2008 2:38:16 AM
Reply:

Similar Artilces:

Finding Controls from User Control issue. C#.NET 1.1
Okay, I have a user control that opperates on a DataGrid. I have a Page which has a DataGrid my userControll on it. My User Control needs to operate on that Datagrid (and hold it's formation through post-backs, not in the viewstate). So the only thing I can think of is to find the DataGrid by it's name, which is set in the html as the public property string DataGridName: public string DataGridName         {             set             {     &n...

Sending SMS using vb.net or C#.net using vb.net or c#.net
Hi  My requirement is I hav one csv file with these fields id,mobilenum,messgae,status.intiallu staus is 0. once i read the all fileds and take that mobile number.using tat mobile number  i need to send sms .after sending sms i shuld change status as 1 How to send sms thru coding (please dont provide any links.if it is provide also please give working links becox i checked codeproject .i didnt get any nice link. and also provide the how to update the status field im csv file   Thank ssandhya   To send SMS, you need some third party SMS providers. if you consul...

want to call one c#.net function in one user control from another user control
hi i have two user controls info.ascx and personal.ascx i have a function like in info.ascx i have a function like showdetails() {   } now i want to access this function from personal.ascx can i do this ? thanks in advance. shwetaThanksshwetaIn a day when don't come across any problem -you can be sure that you are traveling in wrong path  you should better create a class where you will define the "functions" that you need in both files. declare "static" the function and call it like nameofclass.nameoffunction In a web project you can...

Master Details in two seperate GridView Controls
I am simply trying to have a list of people in the top grid control (works fine), then when selected have the second Grid Control show details for that person(not working). Here is what I am trying from the load event: Sub BindData() Dim myConnection As New MySql.Data.MySqlClient.MySqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionSql")) Dim strPersonSQL, strActSQL As String strPersonSQL = "select row_id, first_name, last_name, middle_initial, dsi_id, created, created_by, program_of_study, email from tbl_person" Dim myPerCommand As New MySqlClient.MySqlComm...

Datagrid(.net 1.1) to GridView(.net 2.0) and using the RowUpdating event how to extract the values from the controls.
Ok  This is the settings: I use a Viewgrid with only itemtemplate colums for example. <asp:TemplateField HeaderText="Test"><ItemTemplate><asp:Label id="LBL_Test" text='<%# DataBinder.Eval(Container.DataItem, "Test1") %>' runat="server" meta:resourcekey="LBL_TestResource1"></asp:Label></font></ItemTemplate> <EditItemTemplate><asp:TextBox ID="HDN_Test" Text='<%# DataBinder.Eval(Container.DataItem, "Test1") %>' Runat="server" meta:resourcekey="HDN_TestResource1" /></EditItemTemplate></asp:TemplateField>  The ...

Trouble controlling .net controlls with CSS
 I am trying to control the :hover css property on <asp: Button> controls. Basically the css is working correctly to set the initial look of the button, but nothing is happening when I hover over the button. Here is my code:CSS:.sidebarButton{    width: 168px;     height: 45px;     background-color: #666666;     text-align: left;    font-weight: bold;    font-family: Century Gothic;    font-size: 13pt;    color: White;    border-style: none;  ...

use VB.NET and C#.NET code in the same C#.NET project
All-- Here is a sample that is "off the beaten path", (at least for me). Is it possible, in an ASP.NET application, using the code-behind page building technique, to have both pages written in VB.NET and pages written C#.NET?At http://www.WebLogicArts.com/DemoList.aspx there is a sample that shows that, (contrary to popular belief), it IS possible to mix ASP.NET pages built with C#.NET with ASP.NET pages built with VB.NET in the same VS.NET 2003 project. Note that this is just a "fun" sample to see if it can be done and I do not recommend this practice as a "standard" way of develo...

DW control in VB. NET custom control
Hi Just attempting to investigate some DW.NET aspects. In regards to building a ancestor object with VB.NET, why is when I create a datawindowcontrol custom control that any reference to it is like (assuming that u_dw is the name of the DW control): custom_control.u_dw.DatawindowObject = "myDW" instead of simply: u_dw.DatawindowObject = "myDW" If I create a .NET custom control with a button on it, I can directly reference the button's methods and properties without having to qualify it with the custom control's name. When I was developing with po...

What is the real difference between Server Controls and .NET controls?
This was a class discussion question and I'd like to know, what exactly are the differences? Is there a clear answer? .NET framework controls are server controls. The only difference that I can think of is that the .NET controls are part of the FCL (Framework Class Library). HTH,RyanRyan OlshanASPInsider | Microsoft MVP, ASP.NEThttp://ryanolshan.comHow to ask a question...

Making the .NET calendar control as a floating control
Hi, I need to implement the .NET calendar control as a floating control. Is it possible to do that? If so, can you let me know how to do that?With Regards,Saravana Kumar M R  You could use the calendar extender control in the AJAX control toolkit. You can download the toolkit here, and there is a sample here.My Blog...

Add .Net Control to Web Custom Control
 I want to add .NET Control (like: TextBox, Button...) to Web Custom Control.How i can do it? Alphavn That's called a composite control -- "Mark As Answer" if my reply helped you -- Hello Guys What gunteman said, that is one approach and in most cases the right one.But its also possible to add child controls to a Control thats inherit from WebControl itself. Be sure to implement INamingContainer to that inherited Control too, thats the important point of that approach.--Microsoft MVP - Visual Developer ASP / ASP.NET- http://www.aspnetzone.de/blogs/peterbuch...

Architecture: .Net Controls vs. Custom Controls
I'm interested in managing users. i.e. Logins and profiles, etc.My question is, should I be using things like the Login control or should I program these from scratch? I dont like the fact that .NET creates so many things for me. This level of abstraction terrifies me and it feels like I have no control over the code .I've done a few huge sites in Classic ASP (million-hits-per-day type sites) and I'm not sure how robust certain controls are, or when to use them.Is, for example, the Login control aimed at newbies to .NET? Should it be used for the larger projects with thousands of...

gridview control in another gridview control
Hi ia have a questioni have a gridview control which contains button in one colum.now my question is i need another gridview to be placed in the  first gidviewso that when i click on the button the second gridview will populate the data.now my question is how to place second gridview in first gridview.or is there any approach like first grid itself acting as parent and child.please help me  Hi sirikalavalapalli:                I think nested gridview will help you. Check this link and it will show you how...

Using .Net (C#) ActiveX control within Builder 2009 (C++)
Hi, We are moving one of our applications from Borland C++ Builder 4.5 to the latest builder 2009. There is also an activeX control in our application (Formule One spreadsheet) which is causing problems in this migration. As this control doesn't cover all our future needs, we are thinking about creating our own gridcontrol to use. So I've been playing around and created an example control in .Net and exposed it as a COM object. When I try to add it to my C++ sample project, (Import component and create new package) and compile this package, I get the following error: [BCC32 Erro...

Web resources about - Gridview control in C#.net - asp.net.presentation-controls

GridView SelectedItem Binding Gotcha in WinRT
Last night when I was doing some WinRT hacking I was trying to setup databinding to the selected item in the GridView control and I ran into ...

CNW Group
Home Services Beyond the Wire About CNW Financials Webcasts Events My CNW All News Releases Advanced Search Gridview Latest News Releases All ...

CNW Group
... Services Beyond the Wire About CNW my CNW CNW Access CNW Directories Financials Webcasts Events my CNW All News Releases Advanced Search Gridview ...

CNW Group
Home Services Beyond the Wire About CNW Financials Webcasts Events My CNW All News Releases Add a Filter Gridview Latest News Releases All Today ...

New CmdLets of Powershell 2.0
New CmdLets of Powershell 2.0

Price Drop: Softbox
... objects- create product reflection- changing the background with something more interestingUse it as:- softbox- honeycomb softbox- gridview ...

Profile.aspx: ASP Alliance
.NET,ASP,ASP.NET,SQL,XML,HTML,ADO,ADO.NET,JavaScript,JScript,CSharp,VBScript and VB tutorials from AspAlliance.

Quick Answers - CodeProject
Questions - Free source code and tutorials for Software developers and Architects.; Updated: 25 Oct 2012

DotNetKicks.com - Upcoming stories
DotNetKicks.com is a community based news site edited by our members. It specialises in .NET development techniques, technologies and tools including ...

View Features - ExtendASP
Call 847-681-9827 or Request a Demo View Features Testimonials Pricing About Us Coming Soon ExtendASP exposes every feature, more than any other ...

Resources last updated: 1/9/2016 3:46:11 PM