Monday, March 12, 2012

How to handle linkbutton click?

guys I've met with a problem

I need to create a linkbutton control dynamicaly within a repeater

Dim X As New RepeaterItem(0, ListItemType.Item)

Dim LB As New LinkButton
LB.Text = SomeText
LB.CommandArgument = Value
LB.CausesValidation = True
AddHandler LB.Click, AddressOf PageClick
X.Controls.Add(LB)


Rep.Controls.Add(X)

...


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

Search(3, TryCast(sender, LinkButton).CommandArgument)

End Sub

but when I click that linkbutton it doesn't fire. what I do wrong?

thanks

Make sure you are re-creating this LinkButton each and every PostBack of the Page.


Add a command name to your LinkButton something like "MyLinkButton" then in the ItemCommand repeater event check if the args, hang on I will put up a sample.

ProtectedSub rptMyRepeater_ItemCommand(ByVal sourceAsObject,ByVal eAs System.Web.UI.WebControls.RepeaterCommandEventArgs)Handles rptMyRepeater.ItemCommand

If e.CommandName ="MyLinkButton"Then
' the link button was clicked
EndIf

EndSub


Eah, I need to recreate them, it works now. Is there a way to avoid recreation on every postback?


Sure, if you wanted, you could always have some type of flag stored in your Page's ViewState collection which you can use to re-create your controls or not. However, no re-creation, no event handlers.

Labels: , , , , , , , , , , , , , , ,

How to handle GridView Event Handler of Child GridView

Hi All,

I am developing a website which needs nested gridview control. All things are fine upto binding data to childgrid, but i am not able to handle Event Handler of Edit, Update, Delete, Cancel for Child Grid View.

I am binding the data to child gridview at RowDataBound Event of Parent GridView.


Here is the code for the same :

protected void gridID_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
childgrid = (System.Web.UI.WebControls.GridView)e.Row.Cells[2].FindControl("childgrid");

string comID = gridID.DataKeys[e.Row.DataItemIndex].Value.ToString();
con.Open();

cmd = new SqlCommand("SELECT * FROM Pipeline where CompName ='" + comID.ToString() + "'", con);

childgrid.DataSource = cmd.ExecuteReader();
childgrid.DataBind();
con.Close();
}

}

But when I click Edit Button of Child Grid View, it's not able to open selected row in edit mode. but when we hide child grid and open once again it is opening in edit mode.

Could you please help me with this?


Thanks,


Jay

Hi:

Could you post your aspx? Did you put it in <EditItemTemplate>?

Thanks

Labels: , , , , , , , , , , , , ,

How to handle events for controls within templates?

I have a FormView control, containing an EditItemTemplate with a dropdown listbox. I want to handle the SelectedIndexChanged event so I can hide or show part of the form...

If I double-click the dropdown to create the event handler, I get the function dropdown1_SelectedIndexChanged()... but without " handles Dropdown1.SelectedIndexChanged"

Obviously the dropdown1 control is inside the EditItemTemplate - but it still generates events? how does one get these?

This is getting frustrating: every time I try to design stuff logically in a componentised way, I get kicked in the teeth with a "gotcha". It was easier using classic ASP and just throwing the html out using Response.Write!!

Hello.

I think that you're using vb.net, right? in c# I don't see any trouble with this. Doesn't something like this work in vb.net:

<asp:DropDownListrunat="server"id="T"OnSelectedIndexChanged="p"AutoPostBack="true">

<asp:ListItemText="1"/>

<asp:ListItemText="2"/>

</asp:DropDownList>

then just define the p method without using the handles (but with the normal parameter list).


Ah, many many hanks: I didn't realise thats how it worked (instead of event-based handling). It so frustrated me last night i turned off the PC and polished off a bottle of wine.

That part works at last!

Now all I need to do is figure out how to control my datasource and formview to tell them to open in edit or insert mode by default (and not select).

Labels: , , , , , , , , , , , , , ,

How to handle errors when using GridView and DetailsView without writing any code

It is great that no code is neccessory when using GridView and DetailsView controls together with a SqlDataSource control. Since there is no code, "try.. catch.. finally" can not be used (nowhere to place the code block). I am wondering how the errors can be trapped and displayed. We certainly do not want users to see a generic .net error page. Can anyone give me some information on this? thanks,

Tom

I guess no one has noticed this question. Let me rephrase it. I really need some help on this. How can you use "try...catch..finally" to handle errors when working with GridView, DetailsView and SqlDataSource controls without writing any code? Or how and where to add error handling code? Thanks,
This is somewhat of a general answer to your question and it may not be of any help. You could use try-catch blocks that will run when events fired by your aspx page like Page_Load, On_Selecting etc... That way these error catching mechanisms will be in place to handle any abnormal behavior your code might produce during runtime.

Thanks plazma, for the suggestion. In fact, I had thought about the way you suggested. It did not work out (or at least I could not figure out how it works). The problem is this. Noramally, the data retrieval and data binding happen inside try.. catch block.

try{
//contact database and bind data to data controls
}
catch{
//handle error
}

However, for the codeless programming, data retrieval and data binding are done automatically by the controls. If the try..catch block is placed in Page_Load or other locations, it could catch some errors but they would not be the data retrieval and databinding related. If let's say there is a permission issue in database, this try..catch block will not be able to catch it because the data retrieval and databinding do not happen inside the block.


I found out that error can be handled in the events (selected, inserted and updated) of the SqlDataSource control:
protected void MySqlDataSource_Selected(object sender, SqlDataSourceStatusEventArgs e){ if (e.Exception != null) { // Mask theerror with a generic message (for security purposes.) lblError.Text = "An exception occurred performing the query."; // Consider theerror handled. e.ExceptionHandled = true; }}

Labels: , , , , , , , , , , , ,

How to handle dynamic control event in repeater?

Hello!

I've met with a problem. I'm building a list of products and use asp.net repeater to display it. each item has to have a LinkButton called "Remove" and I need to handle the click event somehow... :(

Any ideas how to insert a linkbutton into repeater item in a way so I can handle the click event it in the code for all of them?


Put the link button in the repeater

<asp:LinkButton ValidationGroup="Delete" ID="LinkButton1" CommandArgument='<%# Eval("myID") %>">' runat="server" CausesValidation="True"
CommandName="Delete" Text="Delete" OnClick="LinkButton1_Click"></asp:LinkButton>

protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton btn = sender as LinkButton;
String idtoDelete = btn.CommandArgument;
// Run Delete
}

Labels: , , , , , , , , , , , , , ,

How to handle Checkbox in itemtemplate and with the button in gridview

Hi All

I m having a gridview,button control on a form. In thatPatientId is a templatefiled along with a check box.Per page i m goingto display 10 records of a same patient.

My requirement is

1.user has to select only one check box if user selects more than one check box alert or message should be displayed.

2. If user checks only one checkbox i have to pick the particual row. I want to store all the values.

How to handle it.

I m able to get the values with checkbox, but i m unable with the button .

Here is my aspx page code

<asp:GridView ID="Prescgrid" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" BackColor="White" BorderColor="#3366CC" BorderStyle="None"
BorderWidth="1px" CellPadding="4" Height="49px">
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false" CommandName="Refill"
Text="Refill"></asp:LinkButton>

</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Patient_id" SortExpression="patient_id">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%#Bind("patient_id") %>'></asp:TextBox>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Left" Wrap="False" />
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("patient_id") %>'></asp:Label>
<asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack=true OnCheckedChanged="Hai" />
</ItemTemplate>
</asp:TemplateField>

<asp:BoundField DataField="prescription_date" DataFormatString="{0:d}" HeaderText="Prescription Date"
HtmlEncode="False" SortExpression="prescription_date">
<HeaderStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="home_phone" HeaderText="Patient Home Phone" SortExpression="home_phone">
<HeaderStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="pharmacy_phone" HeaderText="Pharmacy Phone" SortExpression="pharmacy_phone">
<HeaderStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="medication1" HeaderText="Medication" SortExpression="medication1">
<HeaderStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="dosage1" HeaderText="Dosage" SortExpression="dosage1">
<HeaderStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="frequency1" HeaderText="Frequency" SortExpression="frequency1">
<HeaderStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="refills" HeaderText="Number Of Refills" SortExpression="refills">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="amt_tablets" HeaderText="Number Of Tablets" SortExpression="amt_tablets">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="staff_comments" HeaderText="Staff Comments" SortExpression="staff_comments">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
</Columns>
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
</asp:GridView>
nbsp;

<asp:Button ID="Button1" runat="server" Text="Button" />

Waiting for valuable replies

Thank u

Baba

Hi Baba,

Now you want to capture the GridViewRow on which the CheckBox is selected on ButtonClick, right?

Try this.

<asp:GridViewID="Prescgrid"runat="server"AllowPaging="True"AllowSorting="True"

AutoGenerateColumns="False"BackColor="White"BorderColor="#3366CC"BorderStyle="None"

BorderWidth="1px"CellPadding="4"Height="49px">

<FooterStyleBackColor="#99CCCC"ForeColor="#003399"/>

<Columns>

<asp:TemplateFieldShowHeader="False">

<ItemTemplate>

<asp:LinkButtonID="LinkButton1"runat="server"CausesValidation="false"CommandName="Refill"

Text="Refill"></asp:LinkButton>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="Patient_id"SortExpression="patient_id">

<EditItemTemplate>

<asp:TextBoxID="TextBox1"runat="server"Text='<%# Bind("patient_id") %>'></asp:TextBox>

</EditItemTemplate>

<HeaderStyleHorizontalAlign="Left"Wrap="False"/>

<ItemTemplate>

<asp:LabelID="Label1"runat="server"Text='<%# Bind("patient_id") %>'></asp:Label>

<asp:CheckBoxID="CheckBox2"runat="server"AutoPostBack="true"OnCheckedChanged="CheckBox2_CheckedChanged"/>

</ItemTemplate>

</asp:TemplateField>

<asp:BoundFieldDataField="prescription_date"DataFormatString="{0:d}"HeaderText="Prescription Date"

HtmlEncode="False"SortExpression="prescription_date">

<HeaderStyleHorizontalAlign="Left"Wrap="False"/>

</asp:BoundField>

<asp:BoundFieldDataField="home_phone"HeaderText="Patient Home Phone"SortExpression="home_phone">

<HeaderStyleHorizontalAlign="Left"Wrap="False"/>

</asp:BoundField>

<asp:BoundFieldDataField="pharmacy_phone"HeaderText="Pharmacy Phone"SortExpression="pharmacy_phone">

<HeaderStyleHorizontalAlign="Left"Wrap="False"/>

</asp:BoundField>

<asp:BoundFieldDataField="medication1"HeaderText="Medication"SortExpression="medication1">

<HeaderStyleHorizontalAlign="Left"Wrap="False"/>

</asp:BoundField>

<asp:BoundFieldDataField="dosage1"HeaderText="Dosage"SortExpression="dosage1">

<HeaderStyleHorizontalAlign="Left"Wrap="False"/>

</asp:BoundField>

<asp:BoundFieldDataField="frequency1"HeaderText="Frequency"SortExpression="frequency1">

<HeaderStyleHorizontalAlign="Left"Wrap="False"/>

</asp:BoundField>

<asp:BoundFieldDataField="refills"HeaderText="Number Of Refills"SortExpression="refills">

<HeaderStyleHorizontalAlign="Left"/>

</asp:BoundField>

<asp:BoundFieldDataField="amt_tablets"HeaderText="Number Of Tablets"SortExpression="amt_tablets">

<HeaderStyleHorizontalAlign="Left"/>

</asp:BoundField>

<asp:BoundFieldDataField="staff_comments"HeaderText="Staff Comments"SortExpression="staff_comments">

<HeaderStyleHorizontalAlign="Left"/>

</asp:BoundField>

</Columns>

<RowStyleBackColor="White"ForeColor="#003399"/>

<SelectedRowStyleBackColor="#009999"Font-Bold="True"ForeColor="#CCFF99"/>

<PagerStyleBackColor="#99CCCC"ForeColor="#003399"HorizontalAlign="Left"/>

<HeaderStyleBackColor="#003399"Font-Bold="True"ForeColor="#CCCCFF"/>

</asp:GridView>

<asp:ButtonID="Button1"runat="server"Text="Button"OnClick="Button1_Click"/>

protectedvoid CheckBox2_CheckedChanged(object sender,EventArgs e)

{

string cScript ="<script>alert('Another CheckBox already checked');</script>";

CheckBox chkCheckBox2 = (CheckBox)sender;

GridViewRow mySelectedRow = ((CheckBox)sender).Parent.ParentasGridViewRow;if(chkCheckBox2.Checked)

{

foreach (GridViewRow gvrin Prescgrid.Rows)

{

if(gvr!=mySelectedRow)

{

if(((CheckBox)gvr.FindControl("CheckBox2")).Checked)

{

ClientScript.RegisterStartupScript(typeof(Page),"clientscript",cScript);

chkCheckBox2.Checked =false;

}

}

}

}

}

protectedvoid Button1_Click(object sender,EventArgs e)

{

string cScript ="<script>alert('First Select a Row');</script>";

bool blnFlag =false;

foreach (GridViewRow gvrin Prescgrid.Rows)

{

if (((CheckBox)gvr.FindControl("CheckBox2")).Checked)

{

//access all elements using myRow.FindControl blah blah

string strPatientID = ((Label)gvr.FindControl("Label1")).Text;blnFlag =true;

}

}

if (!blnFlag)

{

ClientScript.RegisterStartupScript(typeof(Page),"clientscript", cScript);

}

}

Regards,

Naveen

Labels: , , , , , , , , , , , , , , , ,

How to Handle Check box with Button Control

Hi All

I m having a gridview,button control on a form. In that PatientId is a templatefiled along with a check box.Per page i m going to display 10 records of a same patient.

My requirement is

1.user has to select only one check box if user selects more than one check box alert or message should be displayed.

2. If user checks only one checkbox i have to pick the particual row. I want to store all the values.

How to handle it.

I m able to get the values with checkbox, but i m unable with the button .

Here is my aspx page code

<asp:GridView ID="Prescgrid" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" BackColor="White" BorderColor="#3366CC" BorderStyle="None"
BorderWidth="1px" CellPadding="4" Height="49px">
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false" CommandName="Refill"
Text="Refill"></asp:LinkButton>

</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Patient_id" SortExpression="patient_id">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("patient_id") %>'></asp:TextBox>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Left" Wrap="False" />
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("patient_id") %>'></asp:Label>
<asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack=true OnCheckedChanged="Hai" />
</ItemTemplate>
</asp:TemplateField>

<asp:BoundField DataField="prescription_date" DataFormatString="{0:d}" HeaderText="Prescription Date"
HtmlEncode="False" SortExpression="prescription_date">
<HeaderStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="home_phone" HeaderText="Patient Home Phone" SortExpression="home_phone">
<HeaderStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="pharmacy_phone" HeaderText="Pharmacy Phone" SortExpression="pharmacy_phone">
<HeaderStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="medication1" HeaderText="Medication" SortExpression="medication1">
<HeaderStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="dosage1" HeaderText="Dosage" SortExpression="dosage1">
<HeaderStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="frequency1" HeaderText="Frequency" SortExpression="frequency1">
<HeaderStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="refills" HeaderText="Number Of Refills" SortExpression="refills">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="amt_tablets" HeaderText="Number Of Tablets" SortExpression="amt_tablets">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="staff_comments" HeaderText="Staff Comments" SortExpression="staff_comments">
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
</Columns>
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
</asp:GridView>
nbsp;

<asp:Button ID="Button1" runat="server" Text="Button" />

Waiting for valuable replies

Thank u

Baba

You may do better with a DataGrid if you are allowing multiple selections.

http://www.dotnetjohn.com/articles.aspx?articleid=83

Alternately, set up an array as a session variable and populate it with the DataKey for each row on the checkbox_checked event. You should be able to get that out of the event arguments. Then when you do whatever you do, iterate throught the array and pass those datakeys to the SQL statement or whatever you are using as a criteria class.


Hi Baba,

Try this.

http://forums.asp.net/t/1185169.aspx

Regards,

Naveen


Hisrijaya_ramaraju ,

srijaya_ramaraju@.yahoo.com:

1.user has to select only one check box if user selects more than one check box alert or message should be displayed.

You can use javascript to allow user to select only one check box.

srijaya_ramaraju@.yahoo.com:

2. If user checks only one checkbox i have to pick the particual row. I want to store all the values

You can use findcontrol method to get any controls in the row then retrieve it's value.

Have a look at this sample ,

1<div>2 <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">3 <Columns>4 <asp:TemplateField>5 <ItemTemplate>6 <asp:CheckBox ID="CheckBox1" runat="server" />7 </ItemTemplate>8 </asp:TemplateField>9 </Columns>10 </asp:GridView>1112 </div>13 <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

1function check(self)2 {34 var items = document.getElementsByTagName('input');56for(var i =0;i7 {8if(items(i).type =='checkbox' && items(i).id != self.id && items(i).checked ==true)9 items(i).checked =false;10 }11121314 }

1protected void Page_Load(object sender, EventArgs e)2 {3if (!IsPostBack)4 {5 DataTable table =new DataTable();6 table.Columns.Add("age");7 table.Columns.Add("name");8 DataRow dr = table.NewRow();9 dr["age"] = 1;10 dr["name"] ="zz";11 table.Rows.Add(dr);1213 DataRow dr2 = table.NewRow();14 dr2["age"] = 2;15 dr2["name"] ="vv";16 table.Rows.Add(dr2);1718this.GridView1.DataSource = table;19 GridView1.DataBind();20 }212223//this.Button1.Attributes.Add("onclick","check(); return false;");24 }2526protected void Button1_Click(object sender, EventArgs e)27 {28for (int i = 0; i < GridView1.Rows.Count; i++)29 {30 CheckBox chk = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");31if (chk.Checked ==true)32 {33string name = GridView1.Rows[i].Cells[2].Text;//get value here34 }35 }36 }3738protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)39 {40if (e.Row.RowType == DataControlRowType.DataRow)41 {42 CheckBox chk = (CheckBox)e.Row.FindControl("CheckBox1");43 chk.Attributes.Add("onclick","check(this)");44 }45 }

Labels: , , , , , , , , , , , , ,

how to handle addhandler to the dynamically added control in datagrid


Hello friends,
I have a datagrid which contain the conditional checkbox added in the second column of the
datagrid.It is done in the
datagrid's itemdatabound event... It is working fine.
But I want to handle the checkbox's checkchanged event...
As the checkbox is added dynamically, i am trying to use the

AddHandler mychkbox.CheckedChanged,AddressOfMe.mychkbox_CheckedChanged

But at any case, this event is not firing ...
In the following condition,
i.e. I am binding the datagrid in the page_load event.
within the condition as

If (Page.IsPostBack =False)Then

bindgrid()
end if
If i removed the condition above & fire the bindgrid() in the page_load event directly,
then it is firing the event:
AddHandler mychkbox.CheckedChanged,AddressOfMe.mychkbox_CheckedChanged
But for my anothere use i have to fire the binggrid event within the Page.IsPostBack =False
Plz tell me the solution how to fire the
AddHandler mychkbox.CheckedChanged,AddressOfMe.mychkbox_CheckedChanged

Thanks & Regards,
Sandeep.

master_sandy wrote:


Hello friends,
I have a datagrid which contain the conditional checkbox added in the second column of the
datagrid.It is done in the
datagrid's itemdatabound event... It is working fine.


Did you mean that the checkbox would be added to your second column conditionally?? If that is the case you may not be able to use the CheckChanged event handler for your checkbox control at all because any events related to the controls within a DataGrid Control needs to be added within the ItemCreated Event of the DataGrid but this event occurs before the ItemDataBound event and hence if you create your Checkboxes conditionally based on some value coming from the Database in your ItemDataBound event, you would not be able to add the Check Changed event handler to you Control as this event handler along with the Control Creation needs to be done in the ItemCreated event which is before ItemDataBound event chronologically. Write back, how exactly you want to create this checkbox control and I could help you further.
hth

Labels: , , , , , , , , , , , , ,