Solved

ITEMDATABOUND problem,....stuck to retrive value from db..

Posted on 2009-04-14
9
531 Views
Last Modified: 2013-11-07
i have binded the datagrid with delete button , problem here i need to disable the delete button of datagrid if chk column of mytable (tbl1)contains value 1...
 if  chk, contains 0 that row  can be deleted ......how can i retrieve the chk column in the itemdatabound event so that i can able to disable or enable the delete button.,..Plzzzz suggestttttttttttttt.......

tbl1 contains these data's..
id name       chk
1  mathews  1
2  Julie         0
3  King         1
4  Romeo     1
5  Mose       0

<asp:DataGrid ID="DataGrid1" runat="server" AutoGenerateColumns="False" Style="left: 320px;
            position: relative; top: 147px" DataKeyField="id">
            <Columns>
                <asp:TemplateColumn HeaderText="name">
                    <ItemTemplate>
                        <asp:Label ID="label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
                    </ItemTemplate>
                    </asp:TemplateColumn>
                <asp:ButtonColumn CommandName="Delete" HeaderText="Delete" Text="Delete"></asp:ButtonColumn>
            </Columns>
        </asp:DataGrid>


imports System.Data

Imports System.Data.SqlClient

Partial Class deletedisable

    Inherits System.Web.UI.Page

    Dim con As SqlConnection

    Dim Cmd As SqlCommand

 
 

Protected Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGrid1.ItemDataBound

'How can i  retrive chk column value here.......???????????????

            If e.Item.ItemType = ListItemType.EditItem Then

                Dim lb As LinkButton = DirectCast(e.Item.Cells(1).Controls(0), LinkButton)

                lb.Enabled = False

            End If

    
 

    End Sub

 

 

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

        Dim constr As String = ConfigurationManager.AppSettings("con")

        con = New SqlConnection(constr)

        Cmd = New SqlCommand()

        Cmd.Connection = con

        If Not IsPostBack Then

            BindToGrid()

        End If

    End Sub

    Private Sub BindToGrid()

        Cmd = New SqlCommand("Select * from tbl1 ", con)

        Dim ds As New DataSet()

        Dim da As New SqlDataAdapter(Cmd)

        da.Fill(ds)

        DataGrid1.DataSource = ds

        Try

            DataGrid1.DataBind()

        Catch

            DataGrid1.CurrentPageIndex = 0

            BindToGrid()

        End Try

    End Sub

 

    Protected Sub DataGrid1_DeleteCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.DeleteCommand

        Cmd = New SqlCommand("delete from tbl1 where id='" & DataGrid1.DataKeys(e.Item.ItemIndex) & "'", con)

        con.Open()

        Try

            Cmd.ExecuteNonQuery()

        Catch

            Response.Write("Nothing")

        End Try

        DataGrid1.EditItemIndex = -1

        con.Close()

        BindToGrid()

    End Sub
 

 

End Class

Open in new window

0
Comment
Question by:Rajar Ahmed
  • 5
  • 3
9 Comments
 
LVL 10

Expert Comment

by:JPJ78
ID: 24135591
try this. (I haven't tested it, but in theory...)

<asp:Label ID="label1" runat="server" Text='<%# Bind("name") %>' myChk='<%# Eval("chk") %>'></asp:Label>

If e.Item.ItemType = ListItemType.EditItem Then
       Dim lb As LinkButton = DirectCast(e.Item.Cells(1).Controls(0), LinkButton)
       lb.Enabled = Convert.toBoolean(lb.Attributes("MyChk"))
End If
0
 
LVL 18

Author Comment

by:Rajar Ahmed
ID: 24135655
i get this error, in this line....in the catch block/......
 Dim lb As LinkButton = DirectCast(e.Item.Cells(1).Controls(0), LinkButto

Specified argument was out of the range of valid values.
Parameter name: index

 If e.Item.ItemType = ListItemType.Header Then
            Dim lb As LinkButton = DirectCast(e.Item.Cells(1).Controls(0), LinkButton)
            lb.Enabled = Convert.ToBoolean(lb.Attributes("myChk"))
        End If
0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24136122
Don't use indexers to get the control. Instead use

Dim lb As Label= DirectCast(e.Item.FindControl("label1"), Label)
0
 
LVL 18

Author Comment

by:Rajar Ahmed
ID: 24136336
hi GiftsonDJohn,

Now i get this error, in the second line , in catch block..
            lb.Enabled = Convert.ToBoolean(lb.Attributes("label2"))
Object reference not set to an instance of an object.

i dunno whethr i retrieved chk column value correectly or not, plz help me.......

  If e.Item.ItemType = ListItemType.Header Then
            Dim lb As LinkButton = DirectCast(e.Item.FindControl("Delete"), LinkButton)
            lb.Enabled = Convert.ToBoolean(lb.Attributes("label2"))
        End If


 

<asp:DataGrid ID="DataGrid1" runat="server" AutoGenerateColumns="False" Style="left: 320px;

            position: relative; top: 147px" DataKeyField="trid">

             

            <Columns>

                <asp:TemplateColumn HeaderText="name">

                    <ItemTemplate>

                        <asp:Label ID="label1" runat="server" Text='<%# Bind("name") %>' ></asp:Label>

                         <asp:Label ID="label2" runat="server" Text='<%# Bind("chk") %>' ></asp:Label>

                        </ItemTemplate>

                       

                    </asp:TemplateColumn>

                <asp:ButtonColumn CommandName="Delete" HeaderText="Delete" Text="Delete"></asp:ButtonColumn>
 

            </Columns>

        </asp:DataGrid>

Open in new window

0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24136670
Can you tell me what you are planning to do?

also there is no attribute called label2.

<asp:Label ID="label1" runat="server" Text='<%# Bind("name") %>' myChk='<%# Eval("chk") %>'></asp:Label>


Dim lb As Label= DirectCast(e.Item.FindControl("label1"), Label)
lb.Enabled = Convert.ToBoolean(lb.Attributes("myChk"))
0
 
LVL 18

Author Comment

by:Rajar Ahmed
ID: 24136785

Hi GiftsonDjohn,

If i try this code, i get the following error,
Two-way binding is only supported for properties. 'myChk' is not a valid property on 'Label'

<asp:Label ID="label1" runat="server" Text='<%# Bind("name") %>' myChk='<%# Eval("chk") %>'></asp:Label>

Dim lb As Label= DirectCast(e.Item.FindControl("label1"), Label)
lb.Enabled = Convert.ToBoolean(lb.Attributes("myChk"))

This  is my scenario,
Step 1:I binded the datagrid.... with BindToGrid() ,  
Step 2: Datagrid holds 2 columns Name and deletebutton.
Step 3: Now i need to disable or enable the delete button in the datagrid according to value of chk column in database.....
Step 4 : if chk column contains 0 then delete button should be enable
               if chk column contains 1 then delete button should be Disable


Hope this Clear......









This is my  table      |     The output should be like this;

id name       chk      |     (Data Grid Should be Displayed Like this)

1  mathews    1        |     mathews  delete(disable)                            

2  Julie      0        |     julie    delete(enable)    

3  King       1        |     King     delete(disable)   

4  Romeo      1        |     Romeo    delete(disable) 

5  Mose       0        |     Mose     delete(enable)  

Open in new window

0
 
LVL 14

Accepted Solution

by:
GiftsonDJohn earned 500 total points
ID: 24137968
Okay here is the solution.

I have created a datatable based on the table you have shown above. I have created a GridView having columns Name and Chk fields and a template column for delete button.

On the RowDataBound event I am checking whether chk field is true or not. If true then disable the delete button else enable the delete button. I am hiding the chk column in the code behind.

Hope this helps
Code Behind

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) 

    If Not IsPostBack Then 

        Dim dt As New DataTable() 

        dt.Columns.Add("ID") 

        dt.Columns.Add("Name") 

        dt.Columns.Add("Chk") 

        

        Dim dr As DataRow 

        

        dr = dt.NewRow() 

        dr(0) = 1 

        dr(1) = "mathews" 

        dr(2) = True 

        dt.Rows.Add(dr) 

        

        dr = dt.NewRow() 

        dr(0) = 2 

        dr(1) = "Julie" 

        dr(2) = False 

        dt.Rows.Add(dr) 

        

        dr = dt.NewRow() 

        dr(0) = 3 

        dr(1) = "King" 

        dr(2) = True 

        dt.Rows.Add(dr) 

        

        dr = dt.NewRow() 

        dr(0) = 4 

        dr(1) = "Romeo" 

        dr(2) = True 

        dt.Rows.Add(dr) 

        

        dr = dt.NewRow() 

        dr(0) = 5 

        dr(1) = "Mose" 

        dr(2) = False 

        dt.Rows.Add(dr) 

        

        GridView1.DataSource = dt 

        GridView1.DataBind() 

    End If 

End Sub 

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) 

    e.Row.Cells(1).Visible = False 

    

    If e.Row.RowType = DataControlRowType.DataRow Then 

        Dim delbutton As LinkButton = TryCast(e.Row.FindControl("Button1"), LinkButton) 

        Dim chk As Boolean = Convert.ToBoolean(e.Row.Cells(1).Text) 

        

        delbutton.Enabled = Not chk 

    End If 

End Sub 
 
 

Asp.Net Source

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">

            <Columns>

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

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

                <asp:TemplateField ShowHeader="False">

                    <ItemTemplate>

                        <asp:LinkButton ID="Button1" runat="server" CausesValidation="false" CommandName="Delete"

                            Text="Delete" />

                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>

        </asp:GridView>

Open in new window

0
 
LVL 18

Author Comment

by:Rajar Ahmed
ID: 24140644
hi GiftsonDJohn,

i did by binding from database....

Thanksss a lot mate.......

  Protected Sub GridView2_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView2.RowDataBound

        e.Row.Cells(1).Visible = False

        Dim delbutton As LinkButton = TryCast(e.Row.FindControl("Button1"), LinkButton)

        Response.Write(e.Row.Cells(1).Text)

        ' Dim chk As Boolean = Convert.ToBoolean(e.Row.Cells(1).Text)

        If e.Row.Cells(1).Text = "1" Then

            delbutton.Enabled = False

        ElseIf e.Row.Cells(1).Text = "0" Then

            delbutton.Enabled = True

        End If

        'delbutton.Enabled = Not chk

    End Sub

End Class

Open in new window

0
 
LVL 18

Author Closing Comment

by:Rajar Ahmed
ID: 31569799
...thankss again.,...
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Replacing HTML tags in Textarea/Textbox 5 29
Hidden Field Value 10 34
Problem to page 4 26
Red error squiggly on vb.net 7 14
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This video discusses moving either the default database or any database to a new volume.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

760 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now