Gridview under Repeater control in asp.net - asp.net

i have a repeater control which contains grids, based on values from database, say for example i have 2 grids inside repeater control, now both the grids contains a column which have up and down buttons, now when user clicks on the button from any grids, how can i check from which grid the button is called.
below is my code where i am filling the grids on RepeaterItemDataBound Event
GridView gvw = e.Item.FindControl("grid") as GridView;
gvw.DataSource = info.GetStories(sectionNames[e.Item.ItemIndex].Trim());
gvw.DataBind();
here section name contains the name of the sections, based on number of sections, i generate the grids.
My Design looks like this:
<asp:Repeater ID="rptGrids" runat="server"
OnItemDataBound="rptGrids_ItemDataBound">
<ItemTemplate>
<asp:GridView ID="grid" runat="server" Width="100%" CellPadding="5" AllowPaging="true" ShowHeader="true" PageSize="10" AutoGenerateColumns="false" OnRowCommand="Stories_RowCommand">
<Columns>
<asp:BoundField DataField="ArticleID" HeaderText="Article ID" ItemStyle-CssClass="center" />
<asp:BoundField DataField="CategoryID" HeaderText="Category ID" ItemStyle-CssClass="center" />
<asp:BoundField DataField="Title" HeaderText = "Article Title" />
<asp:BoundField DataField="PublishDate" DataFormatString="{0:d}" HeaderText="Publish Date" ItemStyle-CssClass="center" />
<asp:TemplateField HeaderText="Select Action" ItemStyle-CssClass="center">
<ItemTemplate>
<asp:ImageButton ID="btnMoveUp" runat="server" ImageUrl="/images/up.gif" CommandArgument="Up" CommandName='<%# Container.DataItemIndex + "," + DataBinder.Eval(Container.DataItem, "StoryType") %>' />
<asp:ImageButton ID="btnMoveDown" runat="server" ImageUrl="/images/dn.gif" CommandArgument="Down" CommandName='<%# Container.DataItemIndex + "," + DataBinder.Eval(Container.DataItem, "StoryType") %>' />
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="/images/deny.gif" CommandArgument="Delete" OnClientClick="return confirm('Are you sure you want to delete this article?');" CommandName='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:HiddenField ID="hdStoriesSortOrder" runat="server" Value='<%# Eval("SortOrder") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div class="blank"></div>
</ItemTemplate>
</asp:Repeater>
this is my gridviews row_command event
protected void Stories_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandName.Split(',')[0]);
string section = e.CommandName.Split(',')[1].Trim().ToString();
string command = e.CommandArgument.ToString();
if (command.ToLower() == "up")
{
GridView grd = rptGrids.Items[1].FindControl("grid") as GridView; // If i specify the index here, i gets proper grid, but how to recognize at runtime.
Response.Write(grd.Rows.Count);
}
else if (command.ToLower() == "down")
{
}
}
can anyone tell me how can i get from which grid up/down button has been clicked.

You can use command argument to pass required value.
Here is sample of using imagebutton in similar way:
<asp:ImageButton ID="btnView" runat="server" ToolTip="<% $resources:AppResource,Edit %>"
SkinID="EditPage" CommandName="myCommand" CommandArgument='<%# Eval("CustomerId") %>'
PostBackUrl='<%# "~/AdminPages/Customer.aspx?id=" + Eval("CustomerId").ToString() %>' />
Take notice on CommandArgument property.You can set it with value that indicates specific gridview inside repeater.
And here is how to check the value:
protected void EntityGridViewContacts_RowCommand(object sender, GridViewCommandEventArgs e)
{
//here you can check for command name...
switch (e.CommandName)
{
case "myCommand":
//here you access command argument...
int customerId = Convert.ToInt32(e.CommandArgument.ToString());
break;
}
//here is how you access source gridview...
GridView gridView = (GridView)sender;
string controlId = gridView.ID;
}
You can also set CommandArgument using this approach:
CommandArgument='<%# GetMySpecialValue() %>'
Then you should declare function on page side something like this:
public string GetMySpecialValue()
{
return "some value";
}

Related

How can I update all the data in a database specified by selected rows in Asp GridView with a button located outside of the GridView?

I looked for some similar questions, but found only ListView solutions
But I have a GridView and a button outside of the GridView and need to udate only records specified by a selected checkbox.
<asp:GridView ID="gvData"
runat="server" Width = "850px"
CellPadding="5"
AutoGenerateColumns="false"
AllowPaging ="true"
OnPageIndexChanging ="OnPaging" PageSize="5">
<HeaderStyle CssClass="HeaderStyle" />
<PagerStyle CssClass="HeaderStyle" HorizontalAlign="Center" />
<AlternatingRowStyle CssClass="AlternatingRowStyle" />
<RowStyle CssClass="RowStyle" />
<RowStyle HorizontalAlign="Left" />
<Columns>
<asp:TemplateField HeaderText="Id" ItemStyle-Width="20px" Visible="false">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="20px">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked = "false"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Message" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblMessage" runat="server" Width="500px" Text='<%# Eval("Message") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<div style="text-align:left;">
<asp:Button ID="btnChange" runat="server" Text="Change Type" OnClick="btnChange_Click" />
</div>
I have a method btnChange_Click():
protected void btnChange_Click()
{
int index = gvFailedMerchants.SelectedRow.RowIndex;
DbConnection.UpdateMessageType(index);
}
When I click the button, I'm getting the message
"Object reference not set to an instance of an object"
I want to write a logic that where I traverse the grid and add ids of the selected row into one string where all ids are separated by commas:
1,2,3,4,5
Then I will send this string to the stored procedure and use them in a query within IN close:
UPDATE MYTABLE SET column = myValue WHERE ID IN('1,2,3,4,5')
I do not know what is the right approach to the problem.
How can I do that?
Please try this,
<asp:TemplateField HeaderText="Select" ItemStyle-Width="20px">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked = "false"
OnCheckedChanged="ChkSelect_CheckedChanged" data-id='<%# Eval("id") %>'></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
protected void ChkSelect_CheckedChanged(object sender, EventArgs e)
{
try
{
CheckBox chkSel = sender as CheckBox;
string id= chkSel.Attributes["data-id"].ToString();
if (chkSel.Checked == true)
{
Session["ID"] += (Session["ID"].ToString() == "" ? id: "," + id);
}
else
{
string existingCodes = Session["ID"].ToString();
Session["ID"] = existingCodes.Replace(id, "");
}
protected void btnChange_Click()
{
string ids = Session["ID"].ToString();
DbConnection.UpdateMessageType(ids);
}

Get data from the row of a Dropdown in a Gridview

I have a Gridview with a column that has a DropDownList.
I've binded this Dropdownlist with an event on the "SelectedIndexChanged".
The problem is i can't get the value of a label of another column in the same row.
The code is the next:
protected void grid_OnSelectedIndexChanged(object sender, EventArgs e)
{
grdCredenciales.DataBind();
var dropdown = (DropDownList)sender;
var row = (GridViewRow)dropdown.NamingContainer;
var label = (Label)row.FindControl("lblMatricula");
var value = label.Text; // I get "" in this line.
}
And in the grid i have:
<asp:ObjectDataSource ID="CredencialesDS" runat="server" />
<asp:GridView ID="grdCredenciales" runat="server" BackColor="White" DataSourceID="CredencialesDS"
CssClass="DDGridView" RowStyle-CssClass="td" HeaderStyle-CssClass="th" CellPadding="6" AllowSorting="True"
AllowPaging="True" AutoGenerateColumns="False" PageSize="10" OnRowDataBound="grdCredenciales_OnRowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Label7" ToolTip="MatrĂ­cula" runat="server" Text="MatrĂ­cula"/>
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" Width="15%"/>
<ItemStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lblMatricula" runat="server"><%# Eval("Matricula") %></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Label19" ToolTip="Estado" runat="server" Text="Estado" />
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" Width="15%"/>
<ItemStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:DropDownList runat="server" ID="dpEstadoCredencial" AutoPostBack="True" OnSelectedIndexChanged="grid_OnSelectedIndexChanged" CssClass="comboEstado"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I don't know why, but label.text returns an empty string. As you can see, i am calling the DataBind before, so the label should have a value at this point.
Do you know how can i get the value i need from the label in another column?
Thanks for everyone.
Check the GridView's DataSource before you do the DataBind(). Since you're missing the full ASPX markup, I'm not sure if you're setting the data source programmatically or with a SqlDataSource.
In any case, what will happen often with programmatically-set Data Sources is that they disappear on a PostBack, and when you call that DataBind, you're really DataBinding it to null, which would explain why you're getting string.Empty ("") for the Label's Text property.
Just verified the code provided by you. It's working completely.
Please make sure in the RowDataBound event of Grid View, you reattach the dropdownlist's SelectedIndexChanged event as below:
protected void CustomersGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (Page.IsPostBack)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = e.Row.FindControl("dropdown1") as DropDownList;
if (ddl != null)
{
ddl.SelectedIndexChanged += new EventHandler(CustomersGridView_SelectedIndexChanged);
}
}
}
}
Also, I used the same code as yours in SelectedIndexChanged event. I'm putting here my aspx Markup:
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
runat="server"
OnRowDataBound="CustomersGridView_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="Label2" Text='<%# Bind("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="dropdown1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dropdown1_SelectedIndexChanged">
<asp:ListItem Text="Cat"></asp:ListItem>
<asp:ListItem Text="dog"></asp:ListItem>
<asp:ListItem Text="Mouse"></asp:ListItem>
<asp:ListItem Text="pig"></asp:ListItem>
<asp:ListItem Text="snake"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
Please provide your GridView markup too for checking.

delete gridview row Programmatically

I keep returning an error when trying to delete a row in my gridview (Input string was not in a correct format)
Not sure what I'm doing wrong. Any help?
<asp:GridView ID="favoritesGrid" runat="server" OnRowDeleting ="favoritesGrid_RowDeleting">
<columns>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True"/>
<asp:BoundField HeaderText="FavoritesId" DataField="FavoritesId"/>
<asp:TemplateField HeaderText="Site Name">
<ItemTemplate>
<asp:HyperLink ID="myHyperlink"
Text='<%# Eval("SiteName") %>'
NavigateUrl='<%# Eval("Url") %>'
runat="server">
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
protected void favoritesGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var delId = Convert.ToInt32(favoritesGrid.Rows[e.RowIndex].Cells[0].Text);
//var id = favoritesGrid.Rows[e.RowIndex].Cells[0].Text;
var delFavorites = new FavoritesDb();
var delFavs = delFavorites.DeleteFavorite(delId);
DataBind();
}
The cell at position 0 has the word "delete" in it and it cannot be converted to int.
You need to use:
var delId = Convert.ToInt32(favoritesGrid.Rows[e.RowIndex].Cells[1].Text);
However, this is not a good approach since you might change the cells order or add a new one. You'd better use the DataKeyNames attribute.
aspx:
<asp:GridView DataKeyNames="FavoritesId" ...>
C#:
Convert.ToInt32(favoritesGrid.DataKeys[e.RowIndex].Value);

Adding value to TextBox inside Datalist ItemTemplate

I am creating an application, in which I am displaying the images(contained in a folder) in a datalist. Each datalist cell is having a ImageButton(clicking on which will show large pic of the image), a delete button(clicking which will delete the image), a edit button and a textbox. Clicking on the edit button will cause the imagefile name to get displayed in the textbox.
here is my .aspx code
<asp:DataList ID="dtlist" runat="server" RepeatColumns="4" CellPadding="5" EnableViewState="True">
<ItemTemplate>
<asp:ImageButton Width="100" ID="ImagePic" ImageUrl='<%# Container.DataItem %>' CommandName='<%# Container.DataItem %>' runat="server" OnClick="ImagePic_Click" ImageAlign="Top">
</asp:ImageButton>
<br />
<asp:Button Width="100" ID="btn_image_del" CommandName='<%# Container.DataItem %>' runat="server" Text="Delete" OnClick="btn_image_del_Click">
</asp:Button>
<br />
<asp:TextBox ID="txt_image_name" Width="100" runat="server" Visible="True" Text='<%# Container.DataItem %>' MaxLength="500" />
</asp:TextBox>
<asp:Button Width="100" ID="btn_image_edit" CommandName='<%# Container.DataItem %>' runat="server" Text="Edit" OnClick="btn_image_edit_Click">
</asp:Button>
</ItemTemplate>
<ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px" HorizontalAlign="Center" VerticalAlign="Bottom" />
</asp:DataList>
And the .cs code is as follows
protected void BindDataList()//shows the pics from the user folder
{
string[] list = Directory.GetFiles(Server.MapPath("/Candidate_Pics/" + Convert.ToString(Session["Sex"]) + "/" + txt_u_name.Text + "/"));
var aList = from fileName in Directory.GetFiles(Server.MapPath("/Candidate_Pics/" + Convert.ToString(Session["Sex"]) + "/" + txt_u_name.Text + "/"))
select string.Format("/Candidate_Pics/" + Convert.ToString(Session["Sex"]) + "/" + txt_u_name.Text + "/{0}", Path.GetFileName(fileName));
dtlist.DataSource = aList;
dtlist.DataBind();
}
protected void ImagePic_Click(object sender, ImageClickEventArgs e)
{
string strImage = ((ImageButton)sender).CommandName;
ViewState["InsertedURL"] = strImage;
ScriptManager.RegisterStartupScript(Page, typeof(Page), "ShowValidation", "javascript:ShowPic();", true);
Large_Pic.ImageUrl = strImage;
}
protected void btn_image_del_Click(object sender, EventArgs e)
{
string del_selected_image = ((Button)sender).CommandName;
File.Delete(Server.MapPath(del_selected_image));
}
protected void btn_image_edit_Click(object sender, EventArgs e)
{
string edit_selected_image = Path.GetFileName(((Button)sender).CommandName);
// Now what should i do:
}
The above three function namely ImagePic_Click,btn_image_del_Click, btn_image_edit_Click are working fine..Deletion, then LargePic view are all working perfectly, my problem is that, I want that when the edit button will be clicked, the corresponding name of the image will be displayed in the Datalist textbox. In the just above function, edit_selected_image is holding the filename of the corresponding image. I have tested it by applying breakpoints. Now the problem is that I want this value should be passed to the textbox "txt_image_name" in the Datalist.
Try this:
TextBox txt =(TextBox)dtlist.FindControl("txt_image_name");
txt.Text = edit_selected_image;
you need to use EditItemTemplate, for editing Edit Template.
you can write your mark up some tihing like this .
<EditItemTemplate>
PictureName:<asp:Label id="PicutreLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "yourFIleNamePath") %>' runat="server"/> <br />
<asp:LinkButton id="UpdateButton" Text="Update" CommandName="Update" runat="server"/>
<asp:LinkButton id="DeleteButton" Text="Delete" CommandName="Delete" runat="server"/>
<asp:LinkButton id="CancelButton" Text="Cancel" CommandName="Cancel" runat="server"/>

Accessing Details View Bind Data Before The View Is Rendered

I have a field in a details view shown below
<asp:BoundField DataField="DTMON_F" HeaderText="Monday Hours From: " InsertVisible="False"
ReadOnly="True" SortExpression="HOURS" Visible="false" />
<asp:TemplateField HeaderText="Monday Hours From: " SortExpression="HOURS">
<EditItemTemplate>
<uc1:TimePicker ID="tpMondayHours" runat="server"/>
</EditItemTemplate>
<InsertItemTemplate>
<%-- <uc1:TimePicker runat="server" ID="tpMondayHours" />--%>
<asp:TextBox ID="txtMondayHours" runat="server" Text='<%# Bind("DTMON_F") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="lblMondayHours" runat="server" Text='<%# Bind("DTMON_F") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Before "DTMON_F" is binded to the view I want to cut the string that is returned...Where and how might I do this?
You can implement the OnDataBinding event for each control instead of doing the bind inline. This will give you the ability to do whatever you like with the data before assigning it to the control.
Example using your Label. The same could be applied to the TextBox:
<asp:Label ID="lblMondayHours" runat="server"
OnDataBinding="lblMondayHours_DataBinding"></asp:Label>
protected void lblMondayHours_DataBinding(object sender, System.EventArgs e)
{
Label lbl = (Label)(sender);
string yourValue = (int)(Eval("DTMON_F"));
// *** Do whatever you want with the value now
lbl.Text = yourValue;
}

Resources