I've done my research here and I can now succesfully get a value of a hidden boundfield column in my gridview. The problem is I can't target the a hidden column of the row that I selected.
can I use GridView1.SelectedRow.Cells[7].Text; something like that on a hidden column.Is it possible?
here is my code:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//GridView1.Columns[7].Visible = true;
//stock_id_gridview_1();
foreach (GridViewRow row in GridView1.Rows)
{
string id = GridView1.DataKeys[row.RowIndex]["id"].ToString();
con.Open();
cmd = new SqlCommand(#"SELECT transaction_id,transaction_number
FROM stocks_history
WHERE id = #id", con);
cmd.Parameters.AddWithValue("#id", id);
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
transaction_id = rdr["transaction_id"].ToString();
//lbl_test_id.Text = rdr["transaction_id"].ToString();
transaction_number = rdr["transaction_number"].ToString();
lbl_test_id.Text = transaction_id + " " + transaction_number;
}
}
con.Close();
}
here is my gridview:
<asp:GridView ID="GridView1"
CssClass="table table-hover table-striped"
runat="server"
AutoGenerateColumns="False" DataKeyNames="id" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="productName" HeaderText="Product Name"
SortExpression="DateField" />
<asp:BoundField DataField="stock_name" HeaderText="Stock Name"
SortExpression="DateField" />
<asp:BoundField DataField="stock_id" HeaderText="Stock I.D."
SortExpression="DateField" />
<asp:BoundField DataField="stock_in" HeaderText="Stock In"
SortExpression="DateField" />
<asp:BoundField DataField="stock_out" HeaderText="Stock Out"
SortExpression="DateField" />
<asp:BoundField DataField="stock_on_hand" HeaderText="On hand"
SortExpression="DateField" />
<asp:BoundField DataField="max_date" HeaderText="Date & Time"
DataFormatString="{0:MM-dd-yyyy hh:mm tt}"
SortExpression="DateField" />
<asp:BoundField DataField="id" Visible="false" HeaderText="id"
SortExpression="DateField" />
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="HiddenField1" runat="server"
Value='<%# Eval("id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField Text="Select" ControlStyle-CssClass="btn btn-info btn-sm" CommandName="Select" ItemStyle-Width="150" HeaderText="Review">
<ControlStyle CssClass="btn btn-info btn-sm"></ControlStyle>
<ItemStyle Width="150px"></ItemStyle>
</asp:ButtonField>
</Columns>
</asp:GridView>
I wanted to target this bound field:
<asp:BoundField DataField="id" Visible="false" HeaderText="id"
SortExpression="DateField" />
If You use attribute DataKeyNames, you can take value from invisible column like
Use Attribute
<asp:GridView runat="server" ID="GridView" DataKeyNames="id">
</asp:GridView>
And you can access the data
var id = GridView.DataKeys[RowIndex].Values[KeyIndex]
To get selected row hidden column value
var id = GridView.DataKeys[GridView.SelectedRow.RowIndex].Values[0];
Related
I want to change the CSS class behind the tenth BoundField inside my GridView, but I'd like to find it by DataField (i.e., use a string as index).
protected void gdDeliveryDates_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string DeliveryDue = DataBinder.Eval(e.Row.DataItem, "DeliveryDue").ToString();
((LinkButton) e.Row.FindControl("PostDelivery")).Enabled = !String.IsNullOrEmpty(DeliveryDue);
//e.Row.Cells[9].CssClass= "badge";
}
}
In the code above I have commented out the only solution I've found so far, which to me is unacceptable because a column number (i.e., column 9 as specified above) is very volatile. I would prefer to find the column by DataField (a string, in this case, "MailCount" as you'll see in the grid declaration further ahead). Below is what my grid looks like:
<asp:GridView ID="gdDeliveryDates" runat="server" AllowPaging="False" AllowSorting="True" DataSourceID="odsDeliveryDates" AutoGenerateColumns="False" CssClass="table table-striped table-bordered table-hover" OnRowCommand="gdDeliveryDates_RowCommand" OnSelectedIndexChanged="gdDeliveryDates_SelectedIndexChanged" DataKeyNames="PackageOfferedID, PackageID, PostageID, PackageNumber, PackageTitle, PostageName, Section, PostageStart, PostageEnd, DeliveryDue, LName, MailCount, Location" OnRowDataBound="gdDeliveryDates_RowDataBound" >
<Columns>
<asp:BoundField DataField="PackageID" HeaderText="PackageID" Visible="False" ReadOnly="True" SortExpression="PackageID" />
<asp:BoundField DataField="PackageOfferedID" HeaderText="PackageOfferedID" Visible="False" ReadOnly="True" SortExpression="PackageOfferedID" />
<asp:BoundField DataField="PostageID" HeaderText="PostageID" Visible="False" ReadOnly="True" SortExpression="PostageID" />
<asp:BoundField DataField="PackageNumber" HeaderText="Package" Visible="True" ReadOnly="True" SortExpression="PackageNumber" HeaderStyle-CssClass="visible-xs visible-sm visible-md visible-lg" ItemStyle-CssClass="visible-xs visible-sm visible-md visible-lg" />
<asp:BoundField DataField="PostageName" HeaderText="Postage" ReadOnly="True" SortExpression="PostageName" HeaderStyle-CssClass="visible-sm visible-md visible-lg" ItemStyle-CssClass="visible-sm visible-md visible-lg"/>
<asp:BoundField DataField="Section" HeaderText="Section" ReadOnly="True" SortExpression="Section" HeaderStyle-CssClass="visible-xs visible-sm visible-md visible-lg" ItemStyle-CssClass="visible-xs visible-sm visible-md visible-lg" />
<asp:BoundField DataField="PostageStartDate" HeaderText="Start Date" ReadOnly="True" SortExpression="PostageStartDate" DataFormatString="{0:MM/dd/yyyy}" HeaderStyle-CssClass="visible-md visible-lg" ItemStyle-CssClass="visible-md visible-lg" />
<asp:BoundField DataField="PostageEndDate" HeaderText="End Date" ReadOnly="True" SortExpression="PostageEndDate" DataFormatString="{0:MM/dd/yyyy}" HeaderStyle-CssClass="visible-md visible-lg" ItemStyle-CssClass="visible-md visible-lg" />
<asp:BoundField DataField="DeliveryDueDate" HeaderText="Delivery Due" ReadOnly="True" SortExpression="DeliveryDueDate" DataFormatString="{0:MM/dd/yyyy}" HeaderStyle-CssClass="visible-xs visible-sm visible-md visible-lg" ItemStyle-CssClass="visible-xs visible-sm visible-md visible-lg" />
<asp:BoundField DataField="MailCount" HeaderText="#" Visible="True" ReadOnly="True" SortExpression="MailCount" HeaderStyle-CssClass="visible-lg" ItemStyle-CssClass="visible-lg" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="PostDelivery" runat="server" CausesValidation="false" CommandName="Add"
Text="Post Delivery" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
CssClass="buttonLayout" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="LName" HeaderText="LName" Visible="False" ReadOnly="True" SortExpression="LName" />
<asp:BoundField DataField="Location" HeaderText="Location" Visible="False" ReadOnly="True" SortExpression="Location" />
</Columns>
</asp:GridView>
This is not possible but you can try this method:
public int FindIndexByDataField(this GridView gv, string datafieldname)
{
int index = -1, cnum = 0;
foreach (DataControlField col in gv.Columns)
{
if (col is BoundField)
{
BoundField coll = (BoundField)gv.Columns[cnum];
if (coll.DataField == datafieldname)
{
index = cnum;
break;
}
}
cnum++;
}
return index;
}
And call above method like this:
e.Row.Cells[FindIndexByDataField("MailCount")].CssClass= "badge";
I want to access the HyperLinkField column of the GridView from code behind but I am unable to do so.
I have the column in my dataset but I am still not able to use it.
My HyperLinkField column is named Status.
Here is what I tried:
UltraWebGrid1.DataSource = ObjPriDsGrid;
UltraWebGrid1.DataBind();
string StrPriStatus = "";
for (int IntPriI = 0; IntPriI < UltraWebGrid1.Rows.Count; IntPriI++)
{
if (UltraWebGrid1.Rows[IntPriI].Cells[6].Text.Trim() != null)
{
StrPriStatus = UltraWebGrid1.Rows[IntPriI].Cells[6].Text.Trim();
}
else
{
}
if (StrPriStatus == "5")
{
UltraWebGrid1.Rows[IntPriI].Cells[8].Text = ""; // Not getting status column here
}
}
Here is my GridView:
<asp:GridView ID="UltraWebGrid1" ShowHeader="true" runat="server" AutoGenerateColumns="false"
DataKeyNames="mkey" OnRowDataBound="Grid_RowDataBound" Width="98%" Height="30%"
PageSize="10" AllowPaging="true" OnPageIndexChanging="Grid1_PageIndexChanging"
ShowFooter="true" CssClass="Grid">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="../../../Images/plus.png" />
<asp:Panel ID="pnlGrid" runat="server" Style="display: none">
<asp:GridView ID="Grid2" runat="server" AutoGenerateColumns="false" Width="600px"
CssClass="ChildGrid">
<Columns>
<asp:BoundField ItemStyle-Width="80px" DataField="RefMkey" HeaderText="Mkey" />
<asp:BoundField ItemStyle-Width="150px" DataField="CurrentUser" HeaderText="Current User" />
<asp:BoundField ItemStyle-Width="180px" DataField="Department" HeaderText="Current Department" />
<asp:BoundField ItemStyle-Width="100px" DataField="remarks" HeaderText="Remarks" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="0px" DataField="mkey" Visible="false" HeaderText="Mkey" />
<asp:BoundField ItemStyle-Width="8%" DataField="Doc_No" HeaderText="IW/ No" />
<asp:BoundField ItemStyle-Width="10%" DataField="Doc_Date" HeaderText="IW/ Date" />
<asp:BoundField ItemStyle-Width="12%" DataField="DocType" HeaderText="Doc type" />
<asp:BoundField ItemStyle-Width="15%" DataField="Party_Name" HeaderText="Party Name" />
<asp:BoundField ItemStyle-Width="0" Visible="true" DataField="Status_Flag" HeaderText="Status" />
<asp:BoundField ItemStyle-Width="10%" DataField="LastAction_datetime" HeaderText="Last Action Date" />
<asp:BoundField ItemStyle-Width="10%" DataField="CurrStatus" HeaderText="Current Status" />
<asp:BoundField ItemStyle-Width="10%" DataField="Type_desc" HeaderText="Resp Dept" />
<asp:BoundField ItemStyle-Width="12%" DataField="UserName" HeaderText="Resp User" />
<asp:BoundField ItemStyle-Width="8%" DataField="No_Of_Days" HeaderText="No of days" />
<asp:HyperLinkField ItemStyle-Width="5%" DataNavigateUrlFields="Mkey, Status, Doc_No"
DataNavigateUrlFormatString="~/Administration/Dispatch/Inward/FrmInwardNextAction.aspx?Inward_mkey={0}&Status={0}&IWNO={0}"
HeaderText="Status" DataTextField="Status" Target="_blank" />
<asp:HyperLinkField ItemStyle-Width="5%" DataNavigateUrlFields="Mkey, Status, Doc_No"
HeaderText="View" DataTextField="View" Target="_blank" DataNavigateUrlFormatString="~/Administration/Dispatch/Inward/InwardDocDetails.aspx?Key={0}&Status={0}&IWNO={0}" />
</Columns>
</asp:GridView>
Columns like HyperLinkField and CheckBoxField behave a little differently than BoundField. They don't just simply contain text like BoundField. You have to get the control within the cell. You can get the child controls of the cell using the Controls collection. We know that specifically for a HyperLinkField, the HyperLink will be the first control in the collection.
HyperLink hyp = (HyperLink)UltraWebGrid1.Rows[IntPriI].Cells[12].Controls[0];
Can you try it like this
if (StrPriStatus == "5")
{
HyperLink HyperLinkObj = (HyperLink)UltraWebGrid1.Rows[IntPriI].Cells[12].Controls[0];
HyperLinkObj.Text = "";
}
I use this Bulk Edit GridView Control http://aspnetrealworldcontr.codeplex.com/
I use Linq and have a Stored Procedure to update the database.
I don't Understand how to use the Save Button to update the database.
You are suppose to update all the rows with one button.
In the example they use SqlDataSource
example
<div>
<asp:Button runat="server" ID="SaveButton" Text="Save Data" />
<rwg:BulkEditGridView ID="EditableGrid" DataSourceID="PubsDataSource" AutoGenerateColumns="False"
DataKeyNames="au_id" SaveButtonID="SaveButton" runat="server">
<Columns>
<asp:BoundField HeaderText="Last Name" DataField="au_lname" />
<asp:BoundField HeaderText="First Name" DataField="au_fname" />
<asp:BoundField HeaderText="Phone" DataField="phone" />
<asp:BoundField HeaderText="Address" DataField="address" />
<asp:BoundField HeaderText="City" DataField="city" />
<asp:BoundField HeaderText="State" DataField="state" />
<asp:BoundField HeaderText="Zip Code" DataField="zip" />
<asp:CheckBoxField HeaderText="Contract" DataField="contract" />
</Columns>
</rwg:BulkEditGridView>
<asp:SqlDataSource ID="PubsDataSource" runat="server"
SelectCommand="SELECT [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract] FROM [authors]"
UpdateCommand="UPDATE [authors] SET [au_lname] = #au_lname, [au_fname] = #au_fname, [phone] = #phone, [address] = #address, [city] = #city, [state] = #state, [zip] = #zip, [contract]=#contract WHERE [au_id] = #au_id"
ConnectionString="<%$ ConnectionStrings:Pubs %>" />
</div>
My Code - Only the Quantity can be updated.
<cc1:BulkEditGridView ID="CartGrid" runat="server" CssClass="table table-condensed" AutoGenerateColumns="False" GridLines="None" SaveButtonID="UpdateShoppingCart" EnableInsert="False" InsertRowCount="1">
<Columns>
<asp:BoundField DataField="ArtnrFull" HeaderText="Artnr" ReadOnly="True" ItemStyle-Width="10%">
<ItemStyle Width="10%"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="ProductName" HeaderText="Namn" ReadOnly="True" />
<asp:BoundField DataField="Quantity" HeaderText="Antal" ItemStyle-Width="10%">
<ItemStyle Width="10%"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="Pris" DataFormatString="{0:c}" HeaderText="Pris" ReadOnly="True" ItemStyle-Width="20%">
<ItemStyle Width="20%"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="Subtotal" DataFormatString="{0:c}" HeaderText="Subtotal" ReadOnly="True" ItemStyle-Width="20%">
<ItemStyle Width="20%"></ItemStyle>
</asp:BoundField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete" Text="">
<asp:Image ID="Image1" runat="server" ImageUrl="/img/delete.png" Width="20" />
</asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="5%" />
</asp:TemplateField>
<asp:TemplateField Visible="False">
<ItemTemplate>
<asp:Label ID="LblShoppingCartId" runat="server" Text='<%# Bind("ShoppingCartId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</cc1:BulkEditGridView>
<asp:Button ID="UpdateShoppingCart" runat="server" Text="Spara" CssClass="btn btn-success pull-right" />
Stored procedure
CREATE PROCEDURE ShoppingCartUpdateQuantity
#ShoppingCartId int,
#Quantity int,
#ArtnrFull varchar(20)
AS
UPDATE ShoppingCartItems
SET Quantity = #Quantity
WHERE ArtnrFull = #ArtnrFull AND ShoppingCartItems.ShoppingCartId = #ShoppingCartId
Guessing, but this don't runs when i click the button, the grid just disappear.
protected void grdContact_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtQuantity = (TextBox)CartGrid.Rows[e.RowIndex].FindControl("txtQuantity");
Label lblArtnr = (Label)CartGrid.Rows[e.RowIndex].FindControl("lblArtnr");
Label lblShoppingCartId = (Label)CartGrid.Rows[e.RowIndex].FindControl("lblShoppingCartId");
LinqtoDBDataContext db = new LinqtoDBDataContext();
db.ShoppingCartUpdateQuantity(Convert.ToInt32(lblShoppingCartId.Text),Convert.ToInt32(txtQuantity.Text), lblArtnr.Text);
CartGrid.EditIndex = -1;
FillGrid(Convert.ToInt32(lblShoppingCartId.Text));
}
protected void CartGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
if (CartGrid.DirtyRows.Count > 0)
{
Label lblShoppingCartId = (Label)CartGrid.Rows[e.RowIndex].FindControl("lblShoppingCartId");
var cartid = lblShoppingCartId.Text;
//find out which rows were updated
foreach (GridViewRow row in CartGrid.DirtyRows)
{
string lblArtnr = row.Cells[0].Text;
TextBox txtQuantity = row.Cells[2].Controls[0] as TextBox;
LinqtoDBDataContext db = new LinqtoDBDataContext();
db.ShoppingCartUpdateQuantity(Convert.ToInt32(lblShoppingCartId.Text), Convert.ToInt32(txtQuantity.Text), lblArtnr);
}
FillGrid(Convert.ToInt32(cartid));
alertdiv.Attributes.Add("class", "alert alert-success");
alertdiv.Controls.Add(new LiteralControl("Kundvagnen updaterad"));
alertdiv.Visible = true;
}
else
{
alertdiv.Attributes.Add("class", "alert alert-danger");
alertdiv.Controls.Add(new LiteralControl("FEL! Kundvagnen ej updaterad"));
alertdiv.Visible = true;
}
}
catch (Exception)
{
alertdiv.Attributes.Add("class", "alert alert-danger");
alertdiv.Controls.Add(new LiteralControl("FEL! Kundvagnen ej updaterad"));
alertdiv.Visible = true;
}
}
I am databinding the table To grid view, I want to add a column status in the table and the values in the column will be message sent or message saved. I want to display images based on the value is message send or saved. How can I do that dynamically.
DataTable dt = new DataTable();
try
{
string MysqlStatement = "SELECT MsgID, MsgText, RespondBy, ExpiresBy, OwnerName FROM tbl_message WHERE tbl_user_tbl_organisation_OrganisationID = #Value1";
MySqlCommand sqlCmd = new MySqlCommand(MysqlStatement, connectionString);
sqlCmd.Parameters.AddWithValue("#Value1", newOrgID);
MySqlDataAdapter sqlDa = new MySqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
Grid_Messagetable.DataSource = dt;
Grid_Messagetable.DataBind();
Grid_Messagetable.Columns[2].Visible = false;
}
else
{
}
<asp:GridView ID="Grid_Messagetable" runat="server" AllowPaging="True" SelectedIndex="0"
DataKeyNames="MsgID" ShowHeaderWhenEmpty="True" OnRowDeleting="MsgTable_RowDeleting"
OnRowEditing="MsgTable_RowEditing" AutoGenerateColumns="False" BorderStyle="Double"
Width="537px">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" HeaderText="Edit controls"
ButtonType="Image" DeleteImageUrl="~/Styles/Images/Delete.gif" EditImageUrl="~/Styles/Images/Edit.gif" />
<asp:TemplateField HeaderText="DashBoard">
<ItemTemplate>
<asp:ImageButton ID="imgbtn_ViewDashBoard" ImageUrl="Styles/Images/dash.png" Enabled="True"
Width="50" runat="server" PostBackUrl='<%# Eval("MsgID", "ResponseMetric.aspx?MsgID={0}") %>'
Text='Send'></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="MsgID" HeaderText="MsgID" ReadOnly="True" SortExpression="MsgID" />
<asp:BoundField DataField="MsgText" HeaderText="MsgText" ReadOnly="True" SortExpression="MsgText" />
<asp:BoundField DataField="RespondBy" HeaderText="RespondBy" ReadOnly="True" SortExpression="RespondBy" />
<asp:BoundField DataField="ExpiresBy" HeaderText="ExpiresBy" ReadOnly="True" SortExpression="ExpiresBy" />
<asp:BoundField DataField="OwnerName" HeaderText="OwnerName" ReadOnly="True" SortExpression="OwnerName" />
<asp:ImageField DataImageUrlField="Sent" HeaderText="Status"
NullImageUrl="~/Styles/Images/White.gif">
</asp:ImageField>
</Columns>
</asp:GridView>
You can create template column field like this:
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:ImageButton ID="img" runat="server" ImageUrl='<%# (Eval("Status") == "Sent") ? "messagesent.png" : "messagesaved.png" %>' />
</ItemTemplate>
</asp:TemplateField>
Code:
<asp:GridView ID="gv_Recruit" AutoGenerateColumns="False" Width="100%"
runat="server" OnRowCreated="gvStates_RowCreated"
OnRowDataBound="gvStates_RowCreated">
<Columns>
<asp:BoundField HeaderText="key" DataField="key" />
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Quota" DataField="Quota" />
<asp:BoundField HeaderText="Session" DataField="Sess" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:DropDownList ID="ddlCities" Width="100%" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddl_selected">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Recruiter" DataField="Recruiter" />
<asp:BoundField HeaderText="MN Phone" DataField="MN Phone" />
<asp:BoundField HeaderText="Cell Phone" DataField="Cell Phone" />
</Columns>
</asp:GridView>
Code Behind:
protected void ddl_selected(object sender, EventArgs e)
{
string _dd_value = ((DropDownList)sender).SelectedValue;
string trying_to_get = gv_Recruit.Rows[???].Cells[0].Text.ToString();
string also_tried = gv_Recruit.SelectedRow.Cells[0].Text.ToString();
}
Basically what I'm trying to do is get the key value from the first row when the drop down is changed so I can perform an update ???
Can't figure this out.
Thanks in advance for the help...
Try
GridViewRow gRow = (GridViewRow)(sender as Control).Parent.Parent;
string trying_to_get = string.Empty;
if (gRow != null)
{
trying_to_get = gRow.Cells[0].Text;
}