?
Solved

Get the c#  version of code written in VB for a Gridview control.

Posted on 2007-07-29
7
Medium Priority
?
1,685 Views
Last Modified: 2013-11-26
The code below works fine in VB, but i would like to see it in C#. Could someone give me the C# version of the Code below? I've added the VB link given to me from a previous question.
http://www.codeproject.com/useritems/Edit_Xml.asp

----------Web Form

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<A href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</A>">
<html xmlns="<A href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</A>" >
<head runat="<A class=iAs style="FONT-WEIGHT: normal; FONT-SIZE: 100%; PADDING-BOTTOM: 1px; COLOR: darkgreen; BORDER-BOTTOM: darkgreen 0.07em solid; BACKGROUND-COLOR: transparent; TEXT-DECORATION: underline" href="#" target=_blank itxtdid="4163064">server</A>">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="3">
            <Columns>
                <asp:CommandField ShowEditButton="True" />
                <asp:CommandField ShowDeleteButton="True" />
            </Columns>
        </asp:GridView>
        <br />
        <br />
        <br />
        <asp:TextBox ID="txtId" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtTel" runat="server"></asp:TextBox><br />
        <asp:Button ID="Button1" runat="server" Text="Button" /></div>
    </form>
</body>
</html>


---The Page_Load and PageIndexChanging -----
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
   If Page.IsPostBack = False Then
      BindGrid()
   End If
End Sub

Sub BindGrid()
   Dim oDs As New DataSet
   oDs.ReadXml(Request.PhysicalApplicationPath + "XMLFile.xml")
   GridView1.DataSource = oDs
   GridView1.DataBind()
End Sub

Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
   GridView1.PageIndex = e.NewPageIndex
   BindGrid()
End Sub

------- Deleting records
Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
   BindGrid()
   Dim oDs As DataSet = GridView1.DataSource
   oDs.Tables(0).Rows(GridView1.Rows(e.RowIndex).DataItemIndex).Delete()
   oDs.WriteXml(Request.PhysicalApplicationPath + "XMLFile.xml")
   BindGrid()
End Sub

-----------Updating records
Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing
   GridView1.EditIndex = e.NewEditIndex
   BindGrid()
End Sub

Protected Sub GridView1_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GridView1.RowCancelingEdit
   GridView1.EditIndex = -1
   BindGrid()
End Sub

Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating
   ' Get the new values from the GridView controls
   Dim i As Integer = GridView1.Rows(e.RowIndex).DataItemIndex
   Dim strId As String = CType(GridView1.Rows(e.RowIndex).Cells(2).Controls(0), TextBox).Text
   Dim strName As String = CType(GridView1.Rows(e.RowIndex).Cells(3).Controls(0), TextBox).Text
   Dim strTel As String = CType(GridView1.Rows(e.RowIndex).Cells(4).Controls(0), TextBox).Text
   GridView1.EditIndex = -1
   BindGrid()

  ' Update the XML file using the new values
   Dim oDs As DataSet = GridView1.DataSource
   oDs.Tables(0).Rows(i).Item(0) = strId
   oDs.Tables(0).Rows(i).Item(1) = strName
   oDs.Tables(0).Rows(i).Item(2) = strTel
   oDs.WriteXml(Request.PhysicalApplicationPath + "XMLFile.xml")
   BindGrid()
End Sub

--------Creating new records
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
   BindGrid()
   Dim oDs As DataSet = GridView1.DataSource
   Dim oDr As DataRow = oDs.Tables(0).NewRow
   oDr("id") = txtId.Text
   oDr("name") = txtName.Text
   oDr("phone") = txtTel.Text
   oDs.Tables(0).Rows.Add(oDr)
   oDs.WriteXml(Request.PhysicalApplicationPath + "XMLFile.xml")
   BindGrid()
End Sub

 
0
Comment
Question by:bojeff30
  • 3
  • 2
  • 2
7 Comments
 
LVL 14

Expert Comment

by:steveberzins
ID: 19589335
are you willing to do some of this yourself and learn something? I'm hoping so...

the vb code above I don't think as is, will even work, html looks poorly formatted to me.
how in the heck A tags got put into the html, head, and DOCTYPE I'll never guess...

anyway,

I'm assuming you have some flavor of visual studio.

if so, if you create the page in a C# web project, it will shell out quite a bit for you.

and then, the IDE will create the code that hooks up the event handlers for the button and such do much of the heavy lifting for you.

-you paste the parts of code that aren't in the html page, just the ones that are actually valid, the A tags are all messed up in the top of the page, and if you want them in the page, they should be down in the form part of the page.

then
-you double click the button in design view, and it will create the shell of the event handler, and hook the event up for you.

then, steps to convert VB to c# are not rocket science...

subs become void methods

i.e.
Sub BindGrid()

End Sub
becomes
void BindGrid()
{

}

parameters just have the type moved before the name
so in VB a parameter might look like
ByVal sender As Object
in C# it would just be
object sender

Dimming a variable
Dim x as Integer
in C#
int x;

and most lines of code don't change much, but for putting a semi colon at the end.

give it a shot, it really isn't that hard, and if you get stuck on something, we'll help you step by step, put up what you have done, and we'll help you get there.

0
 
LVL 22

Expert Comment

by:DarkoLord
ID: 19589360
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
     <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="3" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
            <Columns>
                <asp:CommandField ShowEditButton="True" />
                <asp:CommandField ShowDeleteButton="True" />
            </Columns>
        </asp:GridView>
        <br />
        <br />
        <br />
        <asp:TextBox ID="txtId" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtTel" runat="server"></asp:TextBox><br />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /></div>
    </form>
</body>
</html>


using System;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

    void BindGrid()
    {
        DataSet oDs = new DataSet();
        oDs.ReadXml(Request.PhysicalApplicationPath + "XMLFile.xml");
        GridView1.DataSource = oDs;
        GridView1.DataBind();
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindGrid();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        BindGrid();
        DataSet oDs = (DataSet)GridView1.DataSource;
        oDs.Tables[0].Rows[GridView1.Rows[e.RowIndex].DataItemIndex].Delete();
        oDs.WriteXml(Request.PhysicalApplicationPath + "XMLFile.xml");
        BindGrid();
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        BindGrid();
    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        // Get the new values from the GridView controls
        int i = GridView1.Rows[e.RowIndex].DataItemIndex;
        string strId = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
        string strName = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
        string strTel = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
        GridView1.EditIndex = -1;
        BindGrid();

        // Update the XML file using the new values
        DataSet oDs = (DataSet)GridView1.DataSource;
        oDs.Tables[0].Rows[i][0] = strId;
        oDs.Tables[0].Rows[i][1] = strName;
        oDs.Tables[0].Rows[i][2] = strTel;
        oDs.WriteXml(Request.PhysicalApplicationPath + "XMLFile.xml");
        BindGrid();
    }

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindGrid();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        BindGrid();
        DataSet oDs = (DataSet)GridView1.DataSource;
        DataRow oDr = oDs.Tables[0].NewRow();
        oDr["id"] = txtId.Text;
        oDr["name"] = txtName.Text;
        oDr["phone"] = txtTel.Text;
        oDs.Tables[0].Rows.Add(oDr);
        oDs.WriteXml(Request.PhysicalApplicationPath + "XMLFile.xml");
        BindGrid();
    }
}
0
 

Author Comment

by:bojeff30
ID: 19589707
The code posted by DarkoLord takes me back to my initial issue, which is getting an exception server error in the application when I click Edit or Delete. Any suggestion for getting passed this issue?

Seen  when Delete command is clicked in GridView:
Exception Details: System.Web.HttpException: The GridView 'GridView1' fired event RowDeleting which wasn't handled

Seen  when Edit command is clicked in GridView:
Exception Details: System.Web.HttpException: The GridView 'GridView1' fired event RowEditing which wasn't handled
0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
LVL 14

Expert Comment

by:steveberzins
ID: 19589870
I cut and pasted his code into a page in my project and it worked perfectly...

did you copy all his code 'exactly'??? including the .aspx page code, especially:
OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
0
 
LVL 22

Accepted Solution

by:
DarkoLord earned 500 total points
ID: 19589896
Strange, works perfectly for me. Did you create the Default.aspx.cs page and pasted the code (after the closing html tag) from my previous post into it?
0
 
LVL 22

Expert Comment

by:DarkoLord
ID: 19589904
Sorry the previous post might have sounded a little confusing... I meant to say if you pasted the codebehind code to the .cs file?
0
 

Author Comment

by:bojeff30
ID: 19590171
updating the ASPX page worked - Thanks All.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses
Course of the Month17 days, 12 hours left to enroll

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question