Repeater displaying only first record with CSS - asp.net

In the below code by using DIV tag repeater is displaying only first one record retrieved from database. By removing DIV tag mbody everything is working fine. But to align the format of the script I started to use this DIV tag but I am unable to view add records. Please check where the error is at.
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer ID="Timer1" runat="server" ontick="Timer1_Tick" Interval="1000" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger controlid="Timer1" eventname="Tick" />
</Triggers>
<ContentTemplate>
<asp:Repeater ID="Shout_Box" runat="server">
<ItemTemplate><div id="mbody">
<%# DataBinder.Eval(Container.DataItem, "Message") %>
</div> </ItemTemplate>
</asp:Repeater><div id="sbox_button">
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /></div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" UpdateMode="Conditional" runat="server">
<ContentTemplate><div id="sb_text"><asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Wrap="true" Width="400" Height="60" /></div></ContentTemplate>
</asp:UpdatePanel>
In the above code 1 repeater, 1 button and 1 textbox are used. By adding text to the textbox and clicking button the textbox's value goes to database and retrieved by using timer. This script is a kind of chat script. But using DIV tag I am unable to display all records :-(
Server side code
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Timer1_Tick(object sender, EventArgs e)
{
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=chatserver;" + "UID=root;" + "PASSWORD=*****;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
try
{
MyConnection.Open();
OdbcCommand cmd = new OdbcCommand("Select message from shoutbox", MyConnection);
OdbcDataReader dr = cmd.ExecuteReader();
ArrayList values = new ArrayList();
while (dr.Read())
{
string ep = dr[0].ToString();
values.Add(new PositionData(ep));
Shout_Box.DataSource = values;
Shout_Box.DataBind();
}
TextBox1.Text = "";
}
catch
{
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=chatserver;" + "UID=root;" + "PASSWORD=*****;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
OdbcCommand cmd = new OdbcCommand("INSERT INTO shoutbox(name, message)VALUES(?, ?)", MyConnection);
cmd.Parameters.Add("#email", OdbcType.VarChar, 255).Value = "tick";
cmd.Parameters.Add("#email", OdbcType.Text).Value = TextBox1.Text;
MyConnection.Open();
cmd.ExecuteNonQuery();
MyConnection.Close();
TextBox1.Text = string.Empty;
UpdatePanel2.Update();
}

Move the databinding out of the while loop:
while (dr.Read())
{
string ep = dr[0].ToString();
values.Add(new PositionData(ep));
}
Shout_Box.DataSource = values;
Shout_Box.DataBind();
It does not make any sense to bind the data after reading every value.

Related

How to update database in SQL Server when I have checkbox in gridview?

I tried to make a message board.
After someone leave message, manager can check message context can be show for others or not.
I use gridView to connect to my SQL Server data, and there is a checkbox in the gridview.
If I checked checkbox, and click "sent" button, SQL Server data will be updated.
If I would like to update checkbox result into SQL Server data, what should I do?
This is my aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="check or not" SortExpression="replyCheck">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("replyCheck") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" Checked='<%# Bind("replyCheck") %>' Enabled="True" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br/>
<asp:Button ID="Button1" runat="server" Text="sent" OnClick="Button1_Click"/>
And this is my aspx.cs - if I use foreach, it can't update into my database
protected void Button1_Click(object sender, EventArgs e)
{
var id = GridView1.DataKeys.ToString();
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox reply = (row.Cells[0].FindControl("CheckBox2") as CheckBox);
if (reply.Checked)
{
SqlConnection sqlConnection = new SqlConnection(getsql);
sqlConnection.Open();
SqlCommand cmd = new SqlCommand($"UPDATE reply SET replyCheck ='1' WHERE (id = {id})", sqlConnection);
cmd.ExecuteNonQuery();
sqlConnection.Close ();
DataBind();
}
}
}
If I use for, it showed error about "datakey array"
protected void Button1_Click(object sender, EventArgs e)
{
var id = GridView1.DataKeys.ToString();
int messageCheck, displayCheck;
SqlConnection sqlConnection = new SqlConnection(getsql);
sqlConnection.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox message = (CheckBox)GridView1.Rows[i].FindControl("CheckBox2");
if (message.Checked == true)
{
messageCheck = 1;
SqlCommand cmd1 = new SqlCommand($"UPDATE reply SET replyCheck = {messageCheck} WHERE (id = {id})", sqlConnection);
cmd1.ExecuteNonQuery();
}
else
{
messageCheck = 0;
SqlCommand cmd2 = new SqlCommand($"UPDATE reply SET replyCheck = {messageCheck} WHERE (id = {id})", sqlConnection);
cmd2.ExecuteNonQuery();
}
}
sqlConnection.Close();
}
Without javascript, how could I do it?
Thanks for you all
Ok, the way this works is that datafields (non templated columns) in the GV use the cells[] collection.
However, for templated columns, we have to use find control.
And also we will use the data keys feature, as that lets us have/use/work with the database PK row ID, but NOT have to display in the markup/grid for users.
Ok, so here is a GV with both datafiles (the cells()), and also check box.
We will select the check boxes, and then with a save button, send changes back to database.
So, our markup:
<div style="width:50%;padding:25px">
<asp:GridView ID="GVHotels" runat="server" class="table borderhide"
AutoGenerateColumns="false" DataKeyNames="ID">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" HeaderStyle-Width="200" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Smoking" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkSmoking" runat="server"
Checked='<%# Eval("Smoking") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Balcony" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkBalcony" runat="server"
Checked='<%# Eval("Balcony") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="cmdSave" runat="server" Text="Save changes" CssClass="btn"/>
</div>
And now our code to fill out above could be say this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL =
new SqlCommand("SELECT * from tblHotels ORDER BY HotelName ", con))
{
con.Open();
GVHotels.DataSource = cmdSQL.ExecuteReader();
GVHotels.DataBind();
}
}
}
And now we see this:
Now, there is two ways we can update the database. We could in fact update using a datatable, and in one whole shot upate the datbase.
but, we just loop the GV, and execute updates. (if I have time, I'll try and post the 2nd more cool approach).
So, our button to update/save changes (for check boxes). Could be this:
protected void cmdSave_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
conn.Open();
string strSQL = "UPDATE tblHotels Set Smoking = #S, Balcony = #B " +
"WHERE ID = #ID";
foreach (GridViewRow gRow in GVHotels.Rows)
{
CheckBox cSmoke = (CheckBox)gRow.FindControl("chkSmoking");
CheckBox cBlacony = (CheckBox)gRow.FindControl("chkBalcony");
int PKID = (int)GVHotels.DataKeys[gRow.RowIndex]["ID"];
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Parameters.Add("#S", SqlDbType.Bit).Value = cSmoke.Checked;
cmdSQL.Parameters.Add("#B", SqlDbType.Bit).Value = cBlacony.Checked;
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
cmdSQL.ExecuteNonQuery();
}
}
}
}
Note how we use row index to get the PK row ID. NOTE the DataKeys setting for the GV. This allows you to use/have/enjoy use of the database PK row ID (named "ID" in this code example), and NOT have to display/include the PK in the GV display.
Note that you would continue to use cells() collection for NON templated columns. But for any templated column - you have to use FindControl on that row, pluck out the control, and then you can have at it in regards to that control value.
We could also pull each GV row into a data table, and execute ONE datatable update into the database. But, as the above code shows - we actually keep the connection open for the update - and thus not a big deal either way.
Kindly check with this code
Protected Sub Button1_Click(sender As Object, e As EventArgs)
For Each row In GridView1.Rows
Dim chk As CheckBox = row.FindControl("CheckBox2")
If chk.Checked Then
'sql update query
Else
End If
Next
End Sub

DropDownList SelectIndexChanged not working?

This seems to be a common problem. I have tried different solutions but its still not working. This is my code.
HTML:
<div class="form-group">
<label for="exampleInputEmail1">Artist *</label>
<asp:DropDownList ID="artistDropdown" runat="server" CssClass="form-control" AutoPostBack="True" OnSelectedIndexChanged="artistDropdown_SelectedIndexChanged" ViewStateMode="Enabled"></asp:DropDownList>
<asp:TextBox ID="mytest" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="artistDropdown" SetFocusOnError="true" ErrorMessage="Required Field" Font-Bold="True" Font-Names="Arial" Font-Size="X-Small" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:Label ID="lblMessage" runat="server" CssClass="help-block" Visible="False">Cant select Artist with no Manager</asp:Label>
</div>
Function: OnSelectedIndexChanged
protected void artistDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedArtist = artistDropdown.SelectedValue;
mytest.Text = selectedArtist;
string query = "Select [Manager ID] from Artist Where ID = '" + selectedArtist + "'";
string myConnection = dbController.connectionString;
SqlConnection conn = new SqlConnection(myConnection);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
object obj = cmd.ExecuteScalar();
if (obj is System.DBNull)
{
artistDropdown.SelectedValue = "";
lblMessage.Visible = true;
}
else
{
lblMessage.Visible = false;
}
conn.Close();
}
I am loading DropDownList in Page_Load() function and AutoPostBack="True" is set for DropDownList.
I have also made a TextBox which is being set to the selectedValue from DropDownList to check if on OnSelectedIndexChanged is firing. But text box remains empty.
What am I doing wrong?
Did you put the binding of your dropdown in the if (!postback) {} ?
If you rebind the list after every postback, you get the value of the first list item when you reach the artistDropdown_SelectedIndexChanged event.
If this item has an empty string value...

force a page refresh from code behind inside the ajax file upload control event

I am using Ajax File Upload to insert some images into my database and also i am using a data-list to display those images.
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server" Height="141px" Width="640px" MaximumNumberOfFiles="100" OnUploadStart="AjaxFileUpload1_UploadStart" OnUploadComplete="AjaxFileUpload1_UploadComplete" OnUploadCompleteAll="AjaxFileUpload1_UploadCompleteAll" />
and the data-list
<asp:DataList ID="dlImages" runat="server" RepeatColumns="3" CellPadding="5">
<ItemTemplate>
<a id="imageLink" href='<%# Eval("ImageName","~/SlideImages/{0}") %>' title='<%#Eval("Description") %>' rel="prettyPhoto[pp_gal]" runat="server" >
<asp:Image ID="Image1" ImageUrl='<%# Bind("ImageName", "~/SlideImages/{0}") %>' runat="server" Width="112" Height="84" />
</a>
</ItemTemplate>
<ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px" HorizontalAlign="Center"
VerticalAlign="Bottom" />
</asp:DataList>
and the code behind as follows :-
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataList();
}
}
protected void BindDataList()
{
con.Open();
SqlCommand command = new SqlCommand("SELECT ImageName,Description from SlideShowTable", con);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dlImages.DataSource = dt;
dlImages.DataBind();
con.Close();
}
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string fileName = Path.GetFileName(e.FileName);
string filePath = "~/SlideImages/";
AjaxFileUpload1.SaveAs(MapPath(filePath + System.IO.Path.GetFileName(e.FileName)));
con.Open();
SqlCommand cmd = new SqlCommand("Insert into SlideShowTable(ImageName,Description) values(#ImageName,#Description)", con);
cmd.Parameters.AddWithValue("#ImageName", fileName);
cmd.Parameters.AddWithValue("#Description", "Some Description");
cmd.ExecuteNonQuery();
con.Close();
BindDataList();
}
protected void AjaxFileUpload1_UploadCompleteAll(object sender, AjaxControlToolkit.AjaxFileUploadCompleteAllEventArgs e)
{
Response.Redirect("~/Demo.aspx");
Server.TransferRequest(Request.Url.AbsolutePath, false);
Response.Redirect(Request.Url.AbsoluteUri);
}
Now the Problem is that on using the conventional ASP file upload control post back happens and page refreshes automatically and my data-list binds and after upload the data-list gets updated with new images. But on using the Ajax File Upload there is no post-back and no refresh happens despite the fact i have tried different things
Response.Redirect("~/Demo.aspx");
Server.TransferRequest(Request.Url.AbsolutePath, false);
Response.Redirect(Request.Url.AbsoluteUri);
but still i cant get the page to refresh and i have to manually refresh the page to get the updated Data-list on my page. Any help or solution is appreciated. Thank You.

how to delete a row on gridview with a JavaScript button and remain on the same page

I am displaying a set of records through gridview, and edit and delete
buttons next to them. I am having a problem in the record deletion section. The behavior I want is the following: the user clicks the button, a JavaScript validation function is called and after the button click the records are deleted, but the user remains on the same page with the rest of the records. How can I do this while remaining on the same page?
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<div>
<br />
<asp:HyperLink NavigateUrl="~/Entry.aspx" runat="server" text="Add New Record" />
</div>
<div>
<asp:GridView runat="server" ID="grdView" AutoGenerateColumns="false" Height="100%"
Width="100%" onselectedindexchanged="grdView_SelectedIndexChanged" >
<Columns>
<asp:BoundField DataField="Prod_Id" HeaderText="product id " HeaderStyle-BackColor="Azure" />
<asp:BoundField DataField="Prod_Name" HeaderText="Product Name" HeaderStyle-BackColor="Azure" />
<asp:BoundField DataField="Unit_Price" HeaderText="Unit Price " HeaderStyle-BackColor="Azure" />
<asp:BoundField DataField="In_Hand" HeaderText="In Hand" HeaderStyle-BackColor="Azure" />
<asp:BoundField DataField="Fixed" HeaderText="Fixed" HeaderStyle-BackColor="Azure" />
<asp:BoundField DataField="Status" HeaderText="Status" HeaderStyle-BackColor="Azure" />
<asp:HyperLinkField DataNavigateUrlFields="Prod_Id" DataNavigateUrlFormatString="edit.aspx?Prod_Id={0}" Text="Edit" />
<asp:ButtonField ButtonType="Link" Text="Delete" />
</Columns>
</asp:GridView>
</div>
</asp:Content>
code behind part
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
binddata();
}
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
void binddata()
{
con = new SqlConnection("Data Source=.\\sqlexpress; initial catalog=PracticeDb; user id=sa; pwd=manager;");
con.Open();
da = new SqlDataAdapter("Select * from Products", con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
grdView.DataSource = ds;
grdView.DataBind();
}
protected void grdView_SelectedIndexChanged(object sender, EventArgs e)
{
var P_id = ds.Tables[0].Rows[0]["Prod_Id"].ToString();
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=.\\sqlexpress; initial catalog=PracticeDb; user id=sa; pwd=manager;");
con.Open();
string qry = "DELETE FROM PRODUCTS WHERE Prod_Id='" +P_id+ "'";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Thanks
You can use row databound event to accomplish this task.
<asp:LinkButton ID="lnkBtnDel" runat="server" CommandName="DeleteRow" OnClientClick="return confirm('Are you sure you want to Delete this Record?');""CommandArgument='<%#Eval("Prod_Id") %>'>Delete</asp:LinkButton>
and in the rowdatabound event you can have
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
//incase you need the row index
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
int Prod_Id= Convert.ToInt32(e.CommandArgument);
//followed by your code
}
}
You can use LinkButton in GridView
<asp:LinkButton ID="lbtnDelete" runat="server" CommandName="delete" title="Delete"
OnClientClick="return confirm('Do you Want to Delete this Record?');"
CommandArgument='<%#Eval("Prod_Id") %>'></asp:LinkButton>
Code Behind
protected void grdView_RowCommand(object sender, GridViewCommandEventArgs e)
{
int P_Id = e.CommandArgument; \\ This will get the Product id in P_Id variable
\\ do your delete code
}
Hi you can get linkbutton using following code:
<asp:TemplateField HeaderText=Quantity>
<ItemTemplate>
<asp:LinkButton ID="lbtnDelete" runat="server" CommandName="delete" title="Delete"
OnClientClick="return confirm('Do you Want to Delete this Record?');"
CommandArgument='<%#Eval("Prod_Id") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
And code behind use below code:
protected void grdView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "delete")
{
int P_Id = e.CommandArgument; \\ This will get the Product id in P_Id variable
\\ do your delete code
}
}

GridView RowCommand Event and Saving Text

I have a GridView set up:
<asp:GridView id="GridView1" Runat="server" AutoGenerateColumns="False" OnRowCommand = "GridView1_RowCommand" EnableViewState="true">
<Columns>
<asp:TemplateField HeaderText="Delete" ItemStyle-HorizontalAlign="Center">
<ItemTemplate><asp:Button runat="server" ID="Delete" ImageUrl="~/images/Close.gif" CommandName="DeleteRow" CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"/></ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Comment" ItemStyle-Width="175px">
<ItemTemplate><textarea class="raTextBox" id="txtItemComment" rows="4" cols="30"></textarea></ItemTemplate></asp:TemplateField>
</Columns>
</asp:GridView>
The RowCommand in code-behind is setup like:
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
If (e.CommandName = "DeleteRow") Then
//do stuff here
The GridView is data bound on Page Load as follows:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
Session("CalledModule") = "RCMT0021"
Else
With ViewState
_intRepor = CInt(.Item("Report"))
End With
End If
DataBind() //Gridview Load
End Sub
My questions:
The row command event is never fired. The page just goes into the ELSE (of Not is Postback) in Page_Load
How can I keep track of what all is typed in the "Comments" column of each row (a TEXTAREA), and save the data to the database when a SAVE CHANGES (form) button is clicked?
Thanks!
UPDATE:
The Grid-View's Databinding is as follows:
Public Sub DataBind()
Dim clsDatabase As New clsDatabase
Dim cmd As New OleDbCommand()
Try
cmd.CommandText = "SELECT A, B FROM WHERE C = ? ORDER BY A"
Dim report As New OleDbParameter("#Report", _intReportNumber)
cmd.Parameters.Add(report)
cmd.Connection = clsDatabase.Open_DB()
Dim dReader As OleDbDataReader
dReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Dim dt As New DataTable
dt.Columns.Add(New DataColumn("PictureURL", GetType(String)))
dt.Columns.Add(New DataColumn("Seq", GetType(Int16)))
dt.Columns.Add(New DataColumn("ReportNumber", GetType(String)))
Do While (dReader.Read())
Dim dr As DataRow = dt.NewRow()
_strComments = dReader(0).ToString
dr("Seq") = dReader.GetInt16(1)
dr("PictureURL") = "GetImages.aspx?report=" + _intReportNumber.ToString + "&seq=" + dReader.GetInt16(1).ToString
dr("ReportNumber") = _intReportNumber.ToString
dt.Rows.Add(dr)
Loop
GridView1.DataSource = dt
GridView1.DataBind()
Catch err As Exception
End Try
End Sub
So basically, the GridView has three visible columns - a comments field, a picture field, and a field with a delete button (image) to delete the picture (and comments, if any) from the database. The 4th column is a hidden one, keeping track of the the Image ID of the images. I didn't include the picture and other columns for simplicity sake.
The user can add comments, and when he clicks a 'SAVE CHANGES' button, the corresponding comments should get saved for the picture.
The 'SELECT IMAGE' opens up a ModalDialogBox which enables the user to select the image. When closed, it causes a postback, and rebinds the gridview to display the image the user just selected. Therefore, I need the GridView to rebind on postback, or a way around this.
The delete imagebutton (in gridview) should delete the image and comments from the database.
Thanks again!
try this structure...
aspx page: (note textarea has runat="server")
<body>
<form runat="server">
<asp:ScriptManager runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand"
EnableViewState="true" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Delete" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button runat="server" ID="Delete" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comment" ItemStyle-Width="175px">
<ItemTemplate>
<textarea runat="server" class="raTextBox" id="txtItemComment" rows="4" cols="30"></textarea></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
var items = new List<string>();
for (int i = 0; i < 10; i++)
{
items.Add(i + ";comment" + i.ToString());
}
GridView1.DataSource = items;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
var idx = Convert.ToInt32(e.CommandArgument);
var cmt = GridView1.Rows[idx].FindControl("txtItemComment") as System.Web.UI.HtmlControls.HtmlTextArea;
cmt.Value = DateTime.Now.ToString();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var item = e.Row.DataItem.ToString().Split(";".ToCharArray());
var del = e.Row.FindControl("Delete") as Button;
del.CommandName = "DeleteRow";
del.CommandArgument = item[0];
var cmt = e.Row.FindControl("txtItemComment") as System.Web.UI.HtmlControls.HtmlTextArea;
cmt.Value = item[1];
}
}

Resources