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
}
Related
After some lengthy experimentation, I discovered that having this line of code on the aspx side:
<EditItemTemplate>
<asp:DropDownList ID="ddl_Project_Owner" runat="server" Width="70px"
DataTextField="Project_Owner" DataValueField="Project_Owner"
SelectedValue='<%# Bind("Project_Owner") %>' >
</asp:DropDownList>
</EditItemTemplate>
caused an index error, but removing the SelectedValue='<%# Bind("Project_Owner") %>' piece allowed the gridview to function properly. The only thing is, when the row goes into edit mode, the dropdown is not filled with the current value. It's blank. I'd like to fill it with the current value.
On the code-behind side, I use this code to fill the dropdown:
protected void DataGrid_ResourceAllocation_EditCommand(object sender, GridViewEditEventArgs e)
{
DataGrid_ResourceAllocation.EditRowStyle.BackColor = System.Drawing.Color.LightYellow;
DataGrid_ResourceAllocation.EditIndex = e.NewEditIndex;
LoadResourceAllocationGrid();
//DataGrid_ResourceAllocation.DataBind();
SqlConnection conn = GetConnection();
int RAC = DataGrid_ResourceAllocation.Rows.Count;
GridViewRow row = DataGrid_ResourceAllocation.Rows[e.NewEditIndex];
//*********************************************************
//******** Fill in all your dropdown lists here ***********
//*********************************************************
DropDownList ddList = row.FindControl("ddl_Project_Owner") as DropDownList;
string ddListVal = ddList.SelectedValue;
//DropDownList ddList = (DropDownList)e.Row.FindControl("ddl_Project_Owner");
if (ddList != null)
{
//bind dropdown-list
string sqlStr = "Select distinct Project_Owner from tblProjectHealth order by Project_Owner";
DataSet ds = new DataSet();
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(ds);
ddList.DataSource = ds;
ddList.DataTextField = "Project_Owner";
ddList.DataValueField = "Project_Owner";
ddList.DataBind();
//DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["category_name"].ToString();
ddList.SelectedValue = ddListVal;
}
}
I tried that "ddListVal" variable because I thought it might work, but it didn't, so you can ignore that.
Can anyone help me get my dropdown to populate with the current value that exists for that field in that record?
This error is due to this : you set selectedValeue befor binding dropdownlist.
you can bind dropdownlist in RowDataBound
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddList= e.Row.FindControl("ddl_Project_Owner") as DropDownList;
if (ddList != null)
{
string sqlStr = "Select distinct Project_Owner from tblProjectHealth order by Project_Owner";
DataSet ds = new DataSet();
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(ds);
ddList.DataSource = ds;
ddList.DataTextField = "Project_Owner";
ddList.DataValueField = "Project_Owner";
ddList.DataBind();
}
}
}
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.
i have a data grid view combo box column in my data grid view. On on load event of form i am loading the companies name in combo box column and through cell formatting event i am giving the default value to data grid view combo box column.
Now if i select different value from combo box column it does not get reflected. means only default value is there.
My code for on load and cell formatting is
public void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
SqlConnection c = new SqlConnection();
c.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='D:\\Documents\\Visual Studio 2008\\Projects\\Accounts\\Accounts\\Database1.mdf';Integrated Security=True;User Instance=True";
c.Open();
if (e.ColumnIndex == 1 && Viewcashvoucher.mk != "")
{
string mky = Viewcashvoucher.mk;
string q = "select * from lgr where main_key ='" + mky + "'";
SqlCommand cmd = new SqlCommand(q, c);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
e.Value = dr["account_n"].ToString();
}
}
c.Close();
}
and on load event is
private void Cash_Voucher_Load(object sender, EventArgs e)
{
string mky = Viewcashvoucher.mk;
SqlConnection c = new SqlConnection();
c.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='D:\\Documents\\Visual Studio 2008\\Projects\\Accounts\\Accounts\\Database1.mdf';Integrated Security=True;User Instance=True";
c.Open();
string q = "select max(date) from lgr ";
SqlCommand cmd = new SqlCommand(q, c);
SqlDataReader rd = cmd.ExecuteReader();
try
{
if (rd.Read())
{
DateTime date = rd.GetDateTime(0);
if (date != null)
{
tbdate.Text = date.ToShortDateString();
}
}
}
catch (Exception ex)
{
tbdate.Text = DateTime.Now.ToShortDateString();
}
c.Close();
c.Open();
string q1 = "select account_n from master";
SqlCommand cmd1 = new SqlCommand(q1, c);
SqlDataReader rd1 = cmd1.ExecuteReader();
DataGridViewComboBoxColumn acname = dataGridView1.Columns[1] as DataGridViewComboBoxColumn;
while (rd1.Read())
{
acname.Items.Add(Convert.ToString(rd1["account_n"]));
}
}
actually i am using same data grid view for insert and update operation. i want that as user select different value from combo box list the default value should be replaced by selected one.
thanks in advance...
you can also bind the DataBindingComplete event. The only difference in previous and this answer is #Junaith bind the RowAdded event mean it will call the function every time you add the row. and here in mycase I bound DataBindingComplete event which will fire after the grid is full loaded mean this will call only once and that time it will check the all the checkbox in first column of the grid for all the lines.
mygrid.DataBindingComplete +=
new DataGridViewBindingCompleteEventHandler(mygrid_DataBindingComplete);
then and you have to define a function name as mygrid_DataBindingComplete
private void mygrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridView temp = (DataGridView)sender;
foreach (DataGridViewRow rw in temp.Rows)
{
// here 0 indicating the checbox column is the first column in grid
// first column so index would be 0. true will check the checkbox
rw.Cells[0].Value = true;
}
}
CellFormatting event handler is not the right place to set the default value. CellFormatting occurs whenever the content of the cells needs to be formated for display. Whenever you the change the value in the combobox and accept the value, this event is raised and the default value code resets the user selection.
In DataGridView.RowsAdded you could set the defalut value for the combobox cell for the newly added row(s)
Sample Code:
void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
for (int i = e.RowIndex; i < (e.RowIndex+e.RowCount); i++)
{
dataGridView1.Rows[i].Cells[comboboxcolumn_index].Value = defaultvalue;
}
}
hai you can Just use this on RowAdded Event or DataGridview comboboxcolumn creation time. It will Set the Default Value
comboboxcolumn_Name.DefaultCellStyle.NullValue = "Please Select";
void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
for (int i = e.RowIndex; i < (e.RowIndex+e.RowCount); i++)
{
comboboxcolumn_Name.DefaultCellStyle.NullValue = "Please Select";
}
}
Hi everyone I have problem about dropdown list. I am using dropdown list with datasource. How can I get that value which I selected ?
// I need a if statement here because my programme doesn't know which value of dropdown list selected and I don't know how to use this with datasource.
if(//if I select quiz 1 from dropdown list ,quiz 1 should list questions.)
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString);
string chooce = "Select Quiz from tblQuiz where Quiz=1 ";
SqlCommand userExist = new SqlCommand(chooce, con);
con.Open();
int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());
if (temp == 1)
{
if (rbList.Items[0].Selected == true)
{
string cmdStr = "Select Question from tblQuiz where ID=1";
SqlCommand quest = new SqlCommand(cmdStr, con);
lblque.Text = quest.ExecuteScalar().ToString();
con.Close();
}
You can bind the DropDownList in different ways by using List, Dictionary, Enum, DataSet DataTable.
Main you have to consider three thing while binding the datasource of a dropdown.
DataSource - Name of the dataset or datatable or your datasource
DataValueField - These field will be hidden
DataTextField - These field will be displayed on the dropdwon.
you can use following code to bind a dropdownlist to a datasource as a datatable:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from tblQuiz", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
DropDownList1.DataTextField = "QUIZ_Name";
DropDownList1.DataValueField = "QUIZ_ID"
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
if you want to process on selection of dropdownlist, then you have to change AutoPostBack="true" you can use SelectedIndexChanged event to write your code.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string strQUIZ_ID=DropDownList1.SelectedValue;
string strQUIZ_Name=DropDownList1.SelectedItem.Text;
// Your code..............
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
drpCategory.DataSource = CategoryHelper.Categories;
drpCategory.DataTextField = "Name";
drpCategory.DataValueField = "Id";
drpCategory.DataBind();
}
}
Refer to example at this link. It may be help to you.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.aspx
void Page_Load(Object sender, EventArgs e)
{
// Load data for the DropDownList control only once, when the
// page is first loaded.
if(!IsPostBack)
{
// Specify the data source and field names for the Text
// and Value properties of the items (ListItem objects)
// in the DropDownList control.
ColorList.DataSource = CreateDataSource();
ColorList.DataTextField = "ColorTextField";
ColorList.DataValueField = "ColorValueField";
// Bind the data to the control.
ColorList.DataBind();
// Set the default selected item, if desired.
ColorList.SelectedIndex = 0;
}
}
void Selection_Change(Object sender, EventArgs e)
{
// Set the background color for days in the Calendar control
// based on the value selected by the user from the
// DropDownList control.
Calendar1.DayStyle.BackColor =
System.Drawing.Color.FromName(ColorList.SelectedItem.Value);
}
It depends on how you set the defaults for the dropdown. Use selected value, but you have to set the selected value. For instance, I populate the datasource with the name and id field for the table/list. I set the selected value to the id field and the display to the name. When I select, I get the id field. I use this to search a relational table and find an entity/record.
I am working on my first web project and I need help adding IF logic when using GridView. I have a page (CustomerListPage) that has a GridView item that displays a list of customers(rows) that can be clicked. Once the customer is clicked, the user is redirected to a page called "CustomerUsagePage" which shows the most recent record of this customer. This is what my GridView code looks like for my CustomerListPage:
if (GridView1.SelectedRow.RowIndex == 0)
{
//string selectedUser = GridView1.SelectedRow.Cells[0].ToString();
Response.Redirect("CustomerUsagePage.aspx?Customer_Name=" );
BindGridview();
}
The code for my CustomerUsagePage looks like this:
private void BindControlvalues()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from dbo.CustomerTable", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Close();
DataSet ds = new DataSet();
da.Fill(ds);
Label4.Text = ds.Tables[0].Rows[0][1].ToString();
Label1.Text = ds.Tables[0].Rows[0][0].ToString();
Label2.Text = ds.Tables[0].Rows[0][3].ToString();
Label3.Text = ds.Tables[0].Rows[0][4].ToString();
}
My problem is that I can only add IF logic the page where my GridView is located. I would like to click on a customer and have his data appear on my CustomerUsagePage with an if statement. Is it possible? I know I can do this by adding a page per customer but I dont want to go down that route, it seems to tedious. Does anyone have any suggestions?
You can use GridView-FormView (Master/Detail) Control
Link : http://www.codeproject.com/Articles/16780/GridView-FormView-Master-Detail-Control.
Or you can use classic behavior with ItemCommand event
void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Add")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = CustomersGridView.Rows[index];
.....//Adjust your Response
}
}