Getting the value of Full-Row Clickable Gridview and Display in Textbox - c#

I have a gridview that loads data from a stored procedure.
OBJECTIVE:
to make the full gridview row clickable by hiding the select column in the gridview - I was able to do this by doing the code below in the RowDataBound event.
Next is when I click a full row in the gridview, I should be able to get the data / values from the row selected and display this in the textboxes in the modal pop up to appear. This is for UPDATING / EDITING FUNCTIONS.
Here's what I have got
protected void grdTenant_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Style["display"] = "none";
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] =
"javascript:setMouseOverColor(this);";
e.Row.Attributes["onmouseout"] =
"javascript:setMouseOutColor(this);";
e.Row.Attributes["onclick"] =
Page.ClientScript.GetPostBackClientHyperlink
(this.grdTenant, "Select$" + e.Row.RowIndex);
e.Row.Attributes.Add("onclick", String.Format("javascript:$find('{0}').show();",ModalEditTenant.ClientID ));
//this line does not work in retrieving row data
IDataRecord dataRow = (IDataRecord)e.Row.DataItem;
txtRPCode.Text = Convert.ToString(dataRow["Retail Partner"]);
}
}
As an alternative, I do this to achieve the second goal but fails to do the first
protected void grdTenant_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = grdTenant.SelectedRow;
txtRPCode.Text = row.Cells[1].Text;
ModalEditTenant.Show();
}
But, this method works only when the select button column is visible and when it is clicked, it fails to do so when the full row is selected.
How can I make the full row select and retrieves the data to textbox successfully (with the select column hidden)
This is how gridview bind the data from the stored procedure datasource.
System.Threading.Thread.Sleep(500);
//DropDownList ddl = (DropDownList)sender;
SqlCommand cmd = new SqlCommand("spTenantList", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Location", ddlSelectLoc.SelectedValue );
try
{
con.Open();
grdTenant.EmptyDataText = "No Records Found";
grdTenant.DataSource = cmd.ExecuteReader();
grdTenant.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}

Use FindControl()method.
Instead of txtRetailPartner place your TextBox ID.
txtRPCode.Text = ((TextBox)e.Row.FindControl("txtRetailPartner")).Text;

Use my logic below in RowDataBound event to get DataItem:
protected void grdTenant_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Style["display"] = "none";
if (e.Row.RowType == DataControlRowType.DataRow)
{
IDataRecord dataRow = (IDataRecord)e.Row.DataItem;
txtRPCode.Text = Convert.ToString(dataRow["Retail Partner Code"]);
}
}

I have found the answer based on what is to achieved. Using my current codes posted as question , Just remove the one line code there and it will work
protected void grdTenant_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Style["display"] = "none";
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] =
"javascript:setMouseOverColor(this);";
e.Row.Attributes["onmouseout"] =
"javascript:setMouseOutColor(this);";
e.Row.Attributes["onclick"] =
Page.ClientScript.GetPostBackClientHyperlink
(this.grdTenant, "Select$" + e.Row.RowIndex);
}
}
This line is removed:
//This is no longer needed as it will make the onselectedindexchanged event ineffective as this will be run first.
e.Row.Attributes.Add("onclick", String.Format("javascript:$find('{0}').show();",ModalEditTenant.ClientID ));
protected void grdTenant_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = grdTenant.SelectedRow;
txtRPCode.Text = row.Cells[1].Text;
ModalEditTenant.Show();
}
And everything will work as expected.

Related

How can i make a column from GridView(without datasource) readOnly through code? (asp.net C#)

I'm trying to make some columns readonly for not being able to edit them. I have tried a lot of solutions but none of them worked.I am using a gridview without datasource.( I have more tables and i'm displaying them using a dropdownlist).Anyway i want to edit just 2 column or one and i can't do this.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//// this function doesn't work
BoundField bound = GridView1.Columns[0] as BoundField;
bound.InsertVisible = false;
bound.ReadOnly = true;
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
((BoundField)GridView1.Columns[1]).ReadOnly = true;//this doesn't work too
GridViewRow row = GridView1.Rows[e.RowIndex];
string contract_ID = (row.Cells[2].Controls[0] as TextBox).Text;
string room_ID= (row.Cells[6].Controls[0] as TextBox).Text;
string query = "UPDATE CONTRACTE_INCHIRIERE SET ID_CAMERA='"+room_ID+"' WHERE ID_CONTRACT="+contract_ID;
Response.Write(query);
using (OracleCommand cmd = new OracleCommand(query,con))
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
//Reset the edit index.
GridView1.EditIndex = -1;
//Bind data to the GridView control.
SortingBindGrid();
}
Try:
GridView1.ReadOnly = true;
Or this for a single cell:
GridView1.Rows[rowIndex][colName].ReadOnly = true;

DropDownList Selection instead of a TextBox in AutoGenerated Gridview Columns

I bind a Gridview read from my Oracle Database. I have an edit, and delete button. My aim is that when I have a certain table selected and I press my edit button, I replace the first two textboxes with dropdownlists so I restrict what the user can pick in order to run my SQL statement to my database with the selectedvalue in the dropdownlist instead of the textbox value. I have no TemplateFields to reference my columns in the Gridview because they are autogenerated. When I press my update button on my Gridview, it doesn't update from the DropDownList selected value but instead the text value which was in the Gridview. This is a snippet of my code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
//Locate the textboxs I want to replace
TextBox disableJOBRun = e.Row.Cells[2].Controls[0] as TextBox;
TextBox disableAction = e.Row.Cells[3].Controls[0] as TextBox;
//Create the new DropDownLists
DropDownList JobRunSelection = new DropDownList();
DropDownList ActionSelection = new DropDownList();
//Bind the DropDownLists
JobRunSelection.DataSource = ds;
JobRunSelection.DataValueField = "JOBNAME";
JobRunSelection.DataBind();
ActionSelection.DataSource = dsTwo;
ActionSelection.DataValueField = "NAME";
ActionSelection.DataBind();
con.Close();
//Change Text of Textbox
JobRunSelection.SelectedValue = disableJOBRun.Text;
ActionSelection.SelectedValue = disableAction.Text;
//Add the DropdownsLists to the Gridview
e.Row.Cells[2].Controls.Add(JobRunSelection);
e.Row.Cells[3].Controls.Add(ActionSelection);
JobRunSelection.Attributes.Add("runat", "server");
ActionSelection.Attributes.Add("runat", "server");
JobRunSelection.ID = "DropDownJobRunSelection";
ActionSelection.ID = "DropDownActionSelection";
//Hide Textboxes
disableJOBRun.Visible = false;
disableAction.Visible = false;
}
}
protected void GridView1_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
//Get Connection to database
GridViewRow row = GridView1.Rows[e.RowIndex];
String newJobID = ((TextBox)(row.Cells[2].Controls[0])).Text;
String newAction = ((TextBox)(row.Cells[3].Controls[0])).Text;
//Update Table
cmd.CommandText = "UPDATE " + SelectedTable + " SET JOBID = :param2, WHERE " + KeyName + " = " + "'" + KeyValue + "'";
cmd.Parameters.Add(":param2", newJobID);
cmd.Parameters.Add(":param3", newAction);
Perhaps Page_Load resets the text back to its original? If so, how would I go about implementing my DropDownLists? Thanks for any help and I will post any more code necessary.
I solved my problem, I had switched the order of the variables of the Dropdownlist selected value and the text box text. Once I switched them, my text boxes changed their values.

Formatting Cells on Gridview from SQL Data Reader

I have a Grid view which populates through my SQL data reader
Grid View:
<asp:GridView ID="gridviewALL" runat="server" OnItemDataBound="Search_ItemDataBound">
</asp:GridView>
SQL Data Reader:
SqlCommand cmd = new SqlCommand("SELECT en.dpCreatedDT AS 'Time Received', en.enStatusCH AS 'Status', en.enNotificationNoNI AS 'LSBUD Ref', cm.cmpersonfirstch AS 'First Name', cm.cmPersonLastCH AS 'Last Name', cm.cmcompanynamech AS 'Company' FROM dp_enquiry en JOIN dp_caller_master cm ON (en.encmcallerkeyfk = cm.cmCallerKeyNI) WHERE en.ennotificationnoni = #JobnoALL", conn);
try
{
SqlParameter search = new SqlParameter();
search.ParameterName = "#JobnoALL";
search.Value = JobnoALL.Text.Trim();
cmd.Parameters.Add(search);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
gridviewALL.DataSource = dt;
gridviewALL.DataBind();
}
I'm trying to change the format of a cell in the grid view when the text equals a value, I've done this using a listview before but the Gridview steps seems different. I have the following which doesn't seem to be working any suggestions?
private void Search_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
string CurrentColumn = e.Item.Cells[1].Text;
if (CurrentColumn == "PROC")
{
e.Item.Cells[1].Text = "Creating PDF";
}
else if (CurrentColumn == "CLOS")
{
e.Item.Cells[1].Text = "Complete";
e.Item.Cells[1].ForeColor = System.Drawing.Color.Green;
}
}
It must be reading the header, you need to check if its a DataRow:-
if (e.Row.RowType == DataControlRowType.DataRow)
{
string CurrentColumn = e.Item.Cells[1].Text;
//your code goes here..
}
Also, I would suggest you to use DataBinder.Eval method instead to avoid hard-coding of cell index as it may result in error if order of columns change.
string CurrentColumn = DataBinder.Eval(e.Row.DataItem, "yourColumnName").ToString();
Update:
Just noticied you are using ItemDataBound which is an event for DataGrid and not Gridview. Use RowDataBound event instead:-
<asp:GridView ID="gridviewALL" runat="server" OnRowDataBound="gridviewALL_RowDataBound">
</asp:GridView>
Your rowDataBound event should look like this:-
protected void gridviewALL_RowDataBound(object sender, GridViewRowEventArgs e)
{
//your code here
}

No mapping exists from object type System.Web.UI.WebControls.GridViewRow to a known managed provider native type

I want to make a gridview that when I select a row, its values will be populated to another gridview and text boxes, but I am encountering the error above. When I click the row in the GridView2, nothing is happening and an error in the sqladapter occurs. Please help me to fix this code..
Here is my code:
c#
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conn);
SqlCommand com = new SqlCommand("SELECT MRPNo, MRPType, MRPDate FROM MRP WHERE MRPNo = #mrpno",con);
com.Parameters.Add("#mrpno", GridView2.SelectedRow);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(com);
sda.Fill(dt);
DataRow row = dt.Rows[0];
txtMRPNo.Text = row["MRPNo"].ToString();
txtMRPDate.Text = row["MRPType"].ToString();
txtMRPDate.Text = row["MRPDate"].ToString();
GridView3.DataBind();
GridView1.DataBind();
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton selectButton = new LinkButton()
{
CommandName = "Select",
Text = e.Row.Cells[0].Text,
};
e.Row.Cells[0].Controls.Add(selectButton);
}
protected void GridView2_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.ToolTip = "Click to select row";
e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView2, "Select$" + e.Row.RowIndex);
}
}
}
You can not use GridView2.SelectedRow as an input to Parameters.Add(). Please refer to MSDN (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.selectedrow(v=vs.110).aspx) and you will see why.

grid view selected row data

i am getting the data from gridview on rowcommand event by the following code
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "editproject")
{
string rowindex = e.CommandArgument.ToString();
int index = int.Parse(rowindex);
GridViewRow row = GridView2.Rows[index];
Label6.Text = row.Cells[1].Text;
}
}
but it would give only the data of the field that is visible in gridview row .how can i get the field that is not visible but bound to the gridview.
You can't get the value that you set to invisible because these were not rendered at the client side and can't be grabbed on the server side.
Alternatively you can store the value in hidden field and then you can get it from hidden field.
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show(dataGridView1.SelectedRows[0].Cells[0].Value.ToString ());
}
You can,t get the invisible bound elements but you can get the value from data source .For example you save data in data table which assigned to grid .Store this data table in view-state and on row command get data-key of that row and retrieved value through data table
You can get a command-like button which is invisible in the gridview, just look at this:---
False visibility of button requires you to have changed the property EnableEventValidation="False" on the page directive in default.aspx
private void grd_bind()
{
SqlDataAdapter adp = new SqlDataAdapter("select* from tbbook", ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lk = (LinkButton)(e.Row.Cells[5].Controls[0]);
e.Row.Attributes["Onclick"] = ClientScript.GetPostBackClientHyperlink(lk, "");
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = GridView1.SelectedRow.Cells[0].Text;
TextBox2.Text = GridView1.SelectedRow.Cells[1].Text;
TextBox3.Text = GridView1.SelectedRow.Cells[2].Text;
TextBox4.Text = GridView1.SelectedRow.Cells[3].Text;
TextBox5.Text = GridView1.SelectedRow.Cells[4].Text;
}
then in the default.aspx page, set EnableEventValidation
<%# Page Language="VB" EnableEventValidation="false" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

Categories

Resources