gridview arrange strings data right - asp.net

1)Is it possible to arrane strings to the right?
2)Is it possible in case The value of the field is null to have "-" in the corresonding gridview field

protected void Page_Load(object sender, EventArgs e)
{
GridView1.Columns[2].ItemStyle.HorizontalAlign = HorizontalAlign.Right;
}
void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Due to the fact that DBnull value by default would be just empty string
e.Row.Cells[1].Text = (string.IsNullOrEmpty(e.Row.Cells[1].Text))?"-":e.Row.Cells[1].Text;
}
}

Related

Enable/disable a CheckBox column on edit/update

I have grid with a CheckBox column like this:
I want to simply enable the CheckBox of selected row "e" on Edit and disable after Update/Cancel. This is what I have tried:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
((CheckBox)e.Row.FindControl("chkStatus")).Enabled = false;
}
}
catch
{
}
}
This is for enabling the CheckBox on Update/Edit:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = GridView1.Rows[index];
if (e.CommandName == "Edit" || e.CommandName == "Update")
{
((CheckBox)gvRow.FindControl("chkStatus")).Enabled = true;
}
else if (e.CommandName == "Cancel")
{
}
}
But the problem is that after each Edit/Update, RowDataBound fires and disables the CheckBox again.
How can I avoid this?
OK, found the solution.
Just needed to change to:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState != DataControlRowState.Edit)
{
// Here logic to apply only on initial DataBinding...
}
}

Changing the style of specific records in GridView

I'm designing a logistics system in ASP.Net . In the Order processing page, orders are displayed by Grid View,i want to change the font style of the rows to BOLD, which are marked as"ordedr not processed". thanks.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string OrStatus = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Orderstatus"));
if (OrStatus == "Order not processed")
{
//You can use whatever you want to play with rows
e.Row.Cells[0].Font.Bold = true;
e.Row.Cells[2].CssClass = "gridcss";
}
}
}
Follow that code. It will helps
You can do this in "rowdatabound" event of grid.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridView grid = GridView1;
GridViewRow row = e.Row;
if (row.RowType == DataControlRowType.DataRow)
{
string orderstatus= Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Orderstatus"));
if(orderstatus=="Order not processed)
{
//write your code to change css
}
}
}

gridview on select row event

How do I do a grdiview on select row event? On the source page, I added
OnSelectedIndexChanged="grdTanks_OnSelectRow"
in the code behind, I put the function
protected void grdTanks_OnSelectRow(Object sender, GridViewCommandEventArgs e)
{
}
When I try to do it that way, I get No overload for grdTanks_OnSelectRow matches delegate 'System.EventHandler'
If I change the GridViewComandEventArgs to EventArgs, then it won't allow me to do
if (e.CommandName == "Select")
anybody know how to do a OnSelectRow event for a gridview? Thanks
I also added this code:
protected void grdTanks_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowIndex != -1)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.background='#3260a0';;this.style.color='white'";
if (e.Row.RowIndex % 2 == 1)
{
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';this.style.background='white';this.style.color='black'";
}
else
{
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';this.style.background='#bEc8bE';this.style.color='black'";
}
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.grdTanks, "Select$" + Convert.ToString(DataBinder.Eval(e.Row.DataItem, "CargoTankID")));
}
}
}
You could try this:
In the page_load, enter
grdTanks.SelectedIndexChanged +=
and press tab twice. Visual Studio automatically generates the handler for you. The second param would be EventArgs
I think you have to change
protected void grdTanks_OnSelectRow(Object sender, GridViewCommandEventArgs e)
To
protected void grdTanks_SelectedIndexChanged(Object sender, GridViewCommandEventArgs e)
In your code behind
I am not sure what you want to do in this event handler. You are already handling for select event and I think, no need to check again for (e.CommandName == "Select"). (MSDN:The SelectedIndexChanged event is raised when a row's Select button is clicked).
The error said no overload for event and you have to use EventArgs argument.
protected void grdTanks_OnSelectRow(Object sender, EventArgs e)
{
// May be you want like..
// Get the currently selected row using the SelectedRow property.
GridViewRow row = YourGridViewID.SelectedRow;
}

Getting the index of the last row inserted in a GridView

How do I get the row index of the last row inserted in a GridView considering the user may have custom ordering in the grid (I can't use the last row).
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SqlDataSourceCompleteWidget.Insert();
GridViewCompleteWidget.DataBind();
GridViewCompleteWidget.EditIndex = ??????;
}
I want to put the row into edit mode immediately after the insert occurs.
UPDATE
protected void ButtonAdd_Click(object sender, EventArgs e)
{
//SqlDataSourceCompleteWidget.InsertParameters.Add("EFFECTIVE_DATE", Calendar1.SelectedDate.ToString("yyyy-MM-dd"));
SqlDataSourceCompleteWidget.InsertParameters[0].DefaultValue = Calendar1.SelectedDate.ToString("yyyy-MM-dd");
SqlDataSourceCompleteWidget.Insert();
GridViewCompleteWidget.DataBind();
GridViewCompleteWidget.EditIndex = 1;
}
private int mostRecentRowIndex = -1;
protected void GridViewCompleteWidget_RowCreated(object sender, GridViewRowEventArgs e)
{
mostRecentRowIndex = e.Row.RowIndex;
//GridViewCompleteWidget.EditIndex = e.Row.RowIndex;
}
You would want to handle the RowCreated event. You can access the row data and identity/location using the GridViewRowEventArgs object that is passed to this event handler.
void YourGridView_RowCreated(Object sender, GridViewRowEventArgs e)
{
YourGridView.EditIndex = e.Row.RowIndex;
}
Edit using the gridview's onitemcommand. Then you can use a binding expression on the grid column to set whatever you want. If you are using a button or linkbutton or several others you could use the CommandArgument
CommandArgument='<%# Eval("DataPropertyIWant") %>'
Edit
Sorry I skipped that ordering was done by user. I've tested the following code and it works having respected the users ordering of items, but we must take the user to the page where the last row exists.
1st: Retrieve the Max(ID) from database after insertion, store it in a session
select Max(ID) from tbl_name; -- this statement can retrieve the last ID
Session["lastID"]=lastID;
2nd:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
if (Session["lastID"] != null)
if ((int)DataBinder.Eval(e.Row.DataItem, "ID") == (int)Session["lastID"])
{
//Session["rowIndex"] = e.Row.RowIndex;
int rowIndex=e.Row.RowIndex;
if (Session["type"] != null)
if (Session["type"].ToString() == "Normal")
{
int integ;
decimal fract;
integ = rowIndex / GridView1.PageSize;
fract = ((rowIndex / GridView1.PageSize) - integ;
if (fract > 0)
GridView1.PageIndex = integ;
else if (integ > 0) GridView1.PageIndex = integ - 1;
GridView1.EditIndex = rowIndex;
}
}
}
3rd: Convert your commandField into TemplateFields and Set their CommandArgument="Command"
I'll use this argument to identify what triggered RowDataBound event. I store the value in a Session["type"]. The default value is "Normal" defined in the page load event.
if(!IsPostBack)
Session["type"]="Normal";
the other value is set in RowCommand event
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandArgument == "Command")
Session["type"] = "Command";
}
It works for me fine.
Sorry for my language and,may be, unnecessary details.
UPDATE: I worked off of this post
I'm assuming you just return a value after doing the insert but you can set ID wherever you insert the record.
private int mostRecentRowIndex = -1; //edit index
private bool GridRebound = false; //used to make sure we don't rebind
private string ID; //Is set to the last inserted ID
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
//Set so grid isn't rebound on postback
GridRebound = true;
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SqlDataSourceCompleteWidget.InsertParameters[0].DefaultValue = Calendar1.SelectedDate.ToString("yyyy-MM-dd");
ID = SqlDataSourceCompleteWidget.Insert();
GridViewCompleteWidget.DataBind();
}
protected void GridViewCompleteWidget_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Check that the row index >= 0 so it is a valid row with a datakey and compare
//the datakey to ID value
if (e.Row.RowIndex >= 0 && GridViewCompleteWidget.DataKeys[e.Row.RowIndex].Value.ToString() == ID)
{
//Set the edit index
mostRecentRowIndex = e.Row.RowIndex;
}
}
protected void GridViewCompleteWidget_DataBound(object sender, EventArgs e)
{
//Set Gridview edit index if isn't -1 and page is not a post back
if (!GridRebound && mostRecentRowIndex >= 0)
{
//Setting GridRebound ensures this only happens once
GridRebound = true;
GridViewCompleteWidget.EditIndex = mostRecentRowIndex;
GridViewCompleteWidget.DataBind();
}
}
Selects if inserting last record in gridview (no sorting)
You should be able to get the number of rows from the datasource: (minus 1 because the rows start at 0 and the count starts at 1)
GridViewCompleteWidget.EditIndex = ((DataTable)GridViewCompleteWidget.DataSource).Rows.Count - 1;
But put this before you bind the data:
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SqlDataSourceCompleteWidget.Insert();
GridViewCompleteWidget.EditIndex = ((DataTable)GridViewCompleteWidget.DataSource).Rows.Count - 1;
GridViewCompleteWidget.DataBind();
}

How do I get the value of a gridview Cell?

How can I get the value of a gridview cell? I have been trying the code below with no luck.
protected void grvExpirations_RowDataBound(object sender, GridViewRowEventArgs e) {
int test = Convert.toInt32(e.Row.Cells[5].text;
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
if(e.Row.RowType == DataControlRowType.DataRow)
{
string LinkText = (string)System.Web.UI.DataBinder.Eval(e.Row.DataItem, "RegistrationLinkText");
if(LinkText == "text")
{
e.Row.Cells[3].Text = "your text";
}
}
}
protected void grvExpirations_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int test = Convert.toInt32(e.Row.Cells[5].Text);
}
}
use this code below,
protected void grvExpirations_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int test = Convert.ToInt32(Server.HtmlDecode(e.Row.Cells[5].Text.Trim()));
}
}
and please remember cell index number starts from 0
If you use the above methods you will get the value of cell[5] for the last row only.
So if you are specific about a certain row I think you can get the value from any other gridview event handlers.

Resources