I have created on GridView with Label. I have written store procedure to get StatusCode
SELECT StatusCode
From TableName
This line in GridView
< asp:Label ID="lblStatusCode" runat="server" Visible="false"
Text='<%#DataBinder.Eval(Container.DataItem, "StatusCode")%>' />
These lines in .cs file
Label lblStatusCode = (Label)row.FindControl("lblStatusCode");
objJV.Status = Convert.ToInt32(lblStatusCode.Text);
but in lblStatusCode.Text it is showing NULL even though there is value in Table.
When I execute stored procedure independently it is giving values.
// bind function
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindJVJobValidationDetails();
}
}
protected void BindJVJobValidationDetails()
{
JVSummary objJV = new JVSummary();
DataSet dataJobValidation = new DataSet();
if (SessionVariables.PERID != null)
{
dataJobValidation = objJV.GetjvTransaction(SessionVariables.PERID);
gvEmployee.DataSource = dataJobValidation;
gvEmployee.DataBind();
}
}
What might be the problem...?
The text is applied to the control on the page AFTER the code behind runs. Can't you set the text in the code behind?
Edit: You are setting the value of the label on the page i.e aspx / ascx using Container.DataItem but this value is set after the code behind has run. Basically, when the code behind looks at the control it's text property hasn't been set yet. Instead, add a DataRowBinding event to your GridView and set the lblStatusCode.Text in the event in the code behind.
Please try this code on gridview's event
OnRowDataBound="GridView_RowDataBound"
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.DataItem) != null)
{
Label lblStatusCode = (Label)e.row.FindControl("lblStatusCode");
objJV.Status = Convert.ToInt32(lblStatusCode.Text);
}
}
}
Related
I am having trouble attaching a click event onto an image that I have stored within a grid view. Basically it is a delete button that will allow the user to delete a specific row depending on where the button is. I have the code in c# ready for it, however, I cannot seem to attach a click event to it.
This is the markup code of the button
<asp:TemplateField HeaderText="Remove" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="imgbDeleteP" runat="server" BORDER="0" CausesValidation="false" ImageUrl="~/img/Del.png" Height="25px" ImageAlign="Middle"
onClick ="gv_Quals_RowCommand" CommandArgument="<%#Container.DataItemIndex%>" CommandName="Remove" />
</ItemTemplate>
onClick ="gv_Quals_RowCommand"
Here is the code in c# for the click event
protected void gv_Quals_RowCommand(object sender, GridViewCommandEventArgs e)
{
if ((e.CommandName == "Remove"))
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gv_Quals.Rows[index];
DataTable dtCurrentTable = (DataTable)Session["CurrentTable"];
dtCurrentTable.Rows[index].Delete();
if ((dtCurrentTable.Rows.Count < 0))
{
}
else if ((row.Cells[0].Text != "*New*"))
{
int appId = 5000;
//int appId = 1;
string insProg = ("delete from projectunitassignment where UnitId =" + int.Parse(row.Cells[0].Text));
SqlCommand cmd = new SqlCommand(insProg, conn);
cmd.Connection.Close();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
RebindCat(appId);
}
}
}
This is the compilation error that I keep getting
CS0123: No overload for 'gv_Quals_RowCommand' matches delegate 'ImageClickEventHandler'
I cannot set the click event through the properties as it is stored within the grid view so I cannot access it through there. Also the click event does not run as I have tested with debugging
The problem is with GridViewCommandEventArgs should be just EventArgs
public void imgbDeleteP_Click(object sender, EventArgs e)
Edit:
I see that in your code you use the Command Argument, so if you want to use that you should see this post
Basically use onCommand instead of onClick or cast the sender to button to get the command argument, something like:
var argument = ((ImageButton)sender).CommandArgument;
Did you try to associate the click event for that grid during page load ?
I think that is because of GridViewCommandEventArgs which commonly used for RowCommand , change it to EventArgs, so that event should be something like this:
protected void gv_Quals_RowCommand(object sender, EventArgs e)
{
ImageButton btn = (ImageButton)sender;
string cmName= btn.CommandName;
string cmArgument= btn.CommandArgument;
if ((cmName == "Remove"))
{
.....
}
}
or to get row index:
GridViewRow gvRow = (GridViewRow)(sender as Control).Parent.Parent;
int index = gvRow.RowIndex;
The first parent is the GridView Cell and the second parent of the GridView Cell is the GridView Row.
I am trying to format my Gridview columns to display decimal values upto 2 places after the decimal point.
I am aware of both DataFormatString='{0:0.00} for the boundfield and also Eval("NumFailedFiles", "{0:0.00}") for ItemTemplate.
But i want this to be configurable, i.e. i want to get the no. of decimal places from the database and apply to the boundfield or itemtemplate.
For acheiving this i have tried formatting in gridview_RowDataBound Event but in vain.
GridDecimal = Convert.ToInt32(resXResourceSet.GetString("GridMaxDecimals"));
var field = gridView.Columns[1] as BoundField;
field.DataFormatString = "{0:0.00}";
With this code i am encountering an exception which says
"Object reference not set to an instance of an object"
at the 3rd line of the above code.
Can someone help me on how to achieve this for both boundfield and Itemtemplate
This is my datasource to clear the ambiguity
My data source:
You could use the DataBound event which is triggered once after the grid was databound. For example (depends on the actual datasource of your grid):
protected void GridView_DataBound(Object sender, EventArgs e)
{
GridView grid = (GridView)sender;
BoundField col = (BoundField)grid.Columns[1];
int numDecimals = 2; // from database
col.DataFormatString = "{0:N" + numDecimals + "}";
}
If you have a TemplateField use RowDataBound, you should use a lazy-load property like following to avoid that the value has to be loaded for every row:
private int? _NumDecimals;
private int NumDecimals
{
get
{
if (!_NumDecimals.HasValue)
_NumDecimals = GetNumDecimalsFromDB();
return _NumDecimals.Value;
}
set
{
_NumDecimals = value;
}
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// if following doesnt work use the debugger to see the type of e.Row.DataItem
DataRow row = ((DataRowView)e.Row.DataItem).Row;
int numFailedFiles = row.Field<int>("NumFailedFiles");
//presuming that your TemplateField contains a Label with ID="LblNumFailedFiles"
Label LblNumFailedFiles = (Label)e.Row.FindControl("LblNumFailedFiles");
string formatString = String.Format("N{0}", NumDecimals);
LblNumFailedFiles.Text = numFailedFiles.ToString(formatString);
}
}
OnRowDataBound of GridView you have to determine which row type you want to custom like header row, data row, and so on. and also RowDataBound event is raised for every row so you need to access specific row with specific column not gridview .
Solutions 1: If Boundfield is binded with data
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Fetching BoundField Value.
double dbvalue =Convert.ToDouble(e.Row.Cells[ColumnNumber].Text);
e.Row.Cells[ColumnNumber].Text = String.Format("{0:0.00}",dbvalue );
Label lblnum = (Label)e.Row.Cells[ColumnNumber].FindControl("labelID");
lblnum.Text = String.Format("{0:0.00}", integervaluetoformat);
}
}
Solutions 2: (If the Column is a Item Field Template)
In case of ItemTemplate Field no need to fire RowDataBound:
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblnum" runat="server" Text='<%# String.IsNullOrEmpty(Eval("dbcolumn").ToString()) ? "" : string.Format("{0:0.00}",Convert.ToDouble(Eval("dbcolumn").ToString())) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
I have the following code:
<asp:BulletedList ID="filingList" runat="server" DisplayMode="LinkButton"
onclick="filingList_Click">
</asp:BulletedList>
<asp:Literal ID="filingLiteral" runat="server"></asp:Literal>
and in the backend I fill the bulleted list with ListItems (where AlternateFileUrl is a url string that points to text formatted in html):
foreach (ShortFiling file in filingArray)
{
filingList.Items.Add(new ListItem(file.Type.ToString() + " "
+ file.Date.ToString(), file.AlternateHtmlFileUrl));
}
How do I access the text of the value of the item that's clicked on in the filingList then set it to the asp:Literal control? Here is the empty event handler that I defined and assume that I need to put the code in to set the asp:literal to the value of the specified ListItem.
protected void filingList_Click(object sender, BulletedListEventArgs e)
{
//put code here to set the asp:Literal text to
//the value of the item that is clicked on
}
protected void filingList_Click(object sender, BulletedListEventArgs e)
{
var value = filingList.Items[e.Index].Value;
filingLiteral.Text = value;
}
UPDATE 2
Ok you want the text from that URL, keep your markup as it was and change the code behind to this:
protected void filingList_Click(object sender, BulletedListEventArgs e)
{
var value = filingList.Items[e.Index].Value;
using(var client = new WebClient())
{
string downloadString = client.DownloadString(value);
filingLiteral.Text = downloadString;
}
}
You will need to add the System.Net namespace.
If I have understood your question correctly, you would just handle the click event of the BulletedList control, like:
protected void filingList_Click(object sender, BulletedListEventArgs e)
{
BulletedList bull = (BulletedList)sender;
ListItem li = bull.Items(e.Index);
filingLiteral.Text = li.Value;
}
i have a gridview populated by the code below:
protected void CautaProiect_Click(object sender, EventArgs e)
{
wipDBTableAdapters.GetSummaryProiectTableAdapter proiecte = new wipDBTableAdapters.GetSummaryProiectTableAdapter();
SummaryGrid.DataSource = proiecte.GetData(CodProiect.Text);
SummaryGrid.DataBind();
}
The gridview will be populated with some columns with values.
The problem is that the values are formated like this 1234.5600 and i want them to be like 1,234.56
How ca i do this ?
You can format your data in the OnRowDatabound event
sample:
protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label l = (Label)e.Row.FindControl("lblValue");
l.Text = String.Format("{0:C}", l.Text);
}
}
In your GridView columns, use the DataFormatString property and set it to the format you prefer. In your case, you'll want to use "N2".
A great cheatsheet of other formatting options can be found here.
you can use the following code to display in the gridview ItemTemplate
<asp:Label ID="lblFinalPrice" runat="server" Text='<%#Convert.ToDouble(Eval("FinalPrice")).ToString("#.00")%>'></asp:Label>
I have finally managed to find an answer for this :
Here is how :
protected void SummaryGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
double value = Convert.ToDouble(e.Row.Cells[4].Text);
e.Row.Cells[4].Text = value.ToString("#,#.##");
}
I have to set a LinkButton's OnClientClick attribute but I don't know what this value is until the LinkButton is bound to. I'm trying to set the value when the repeater binds, but I can't workout how to get the 'boundItem/dataContext' value...
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:LinkButton Text="HelloWorld" ID="Hyper1" runat="server" OnDataBinding="Repeater1_DataBinding" >
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
var list = new List<TestObject>();
list.Add(new TestObject() {TestValue = "testing1"});
list.Add(new TestObject() { TestValue = "testing2" });
list.Add(new TestObject() { TestValue = "testing3" });
this.Repeater1.DataSource = list;
this.Repeater1.DataBind();
}
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
//link.DataItem ???
}
Is there anyway to find out what the current rows bound item is?
Maybe you need to use ItemDataBound event. It provides RepeaterItemEventArgs argument which has DataItem available
this.Repeater1.ItemDataBound += Repeater1_ItemDataBound;
void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var dataItem = e.Item.DataItem;
}
I assume you are trying to get the value for the row that is currently being databound?
You can change your function to:
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
string valueYouWant = Eval("TestValue").ToString();
// You could then assign the HyperLink control to whatever you need
link.Target = string.Format("yourpage.aspx?id={0}", valueYouWant);
}
valueYouWant now has the value of the field TestValue for the current row that is being databound. Using the DataBinding event is the best way to do this compared to the ItemDataBound because you don't have to search for a control and localize the code specifically to a control instead of a whole template.
The MSDN library had this as a sample event handler:
public void BindData(object sender, EventArgs e)
{
Literal l = (Literal) sender;
DataGridItem container = (DataGridItem) l.NamingContainer;
l.Text = ((DataRowView) container.DataItem)[column].ToString();
}
(see http://msdn.microsoft.com/en-us/library/system.web.ui.control.databinding.aspx)
As you can see it is a simple demonstration of how to access the data item and get data from it. Adapting this to your scenario is an exercise left to the reader. :)