How to implement IF statement using GridView - c#

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
}
}

Related

How to create a datagridview from another one?

I use visual studio 2012: c# winform. I have a datagridview in which 2 columns(Id and society) are created. the datagridview contains 25 records fetched my database.
I also added a button named "Action" to each row in datagridview
Note: In my phpmyadmin database, each society contains many service category and service types
My problem is:
I want that when a button "action" is pressed, all the service category and service type related to that society appear in the same or another datagridview.
Could you help me?
Try somthing like that, you must initiate this function with your main DataGridView, and you will have your "Cloned" DataGridView.
public DataGridView CloneDataGrid(DataGridView mainDataGridView)
{
DataGridView cloneDataGridView = new DataGridView();
if (cloneDataGridView.Columns.Count == 0)
{
foreach (DataGridViewColumn datagrid in mainDataGridView.Columns)
{
cloneDataGridView.Columns.Add(datagrid.Clone() as DataGridViewColumn);
}
}
DataGridViewRow dataRow = new DataGridViewRow();
for (int i = 0; i < mainDataGridView.Rows.Count; i++)
{
dataRow = (DataGridViewRow)mainDataGridView.Rows[i].Clone();
int Index = 0;
foreach (DataGridViewCell cell in mainDataGridView.Rows[i].Cells)
{
dataRow.Cells[Index].Value = cell.Value;
Index++;
}
cloneDataGridView.Rows.Add(dataRow);
}
cloneDataGridView.AllowUserToAddRows = false;
cloneDataGridView.Refresh();
return cloneDataGridView;
}
Hope This Help
If i understand your question correctly, you could use a cell content click event to refill your datatable with the filtered results.
I've done this on one of my forms (see below), however I havent used a phpmyadmin database, only sql, but the logic might be the same.
I should also note that I have the default cell selection as full row select.
For arguments sake, let's say the form shows products, so ProductID, ProductName and ProductType. When we click the button in the grid we want it to filter by the selected row's ProductType.
//First we declare a static string that can be accessed by the whole form
//and blank it so the form doesnt use a previous value.
public static string product_type = ""
//In the form load event, the gridview is populated - this could be moved to anywhere.
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("DB connection string");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Products", conn);
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sqlDataAdap.Fill(ds);
DataTable dt = new DataTable();
sqlDataAdap.Fill(dt);
conn.Close();
}
//In the cell contect click event we give it the ProductType
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//Here we declare a var to identify that we're looking at the row
var row = dataGridView1.CurrentRow.Cells;
//Now we set the string we declared earlier
product_type = Convert.ToString(row["ProductType"].Value);
//Now we repeat the grid script with a parameter which uses our string from above
SqlConnection conn = new SqlConnection("DB connection string");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Products WHERE ProductType = #ProductType", conn);
sc.Parameters.Add("#ProductType", SqlDbType.Int).Value = product_type;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sqlDataAdap.Fill(ds);
DataTable dt = new DataTable();
sqlDataAdap.Fill(dt);
conn.Close();
}
You could then just add a button which repeats the script from the form load event when clicked to return the grid to it's non-filtered state.
Hope this helps.

How to redirect to certain pages depending on what option that I select for dropdownlist?

I have this table called FACILITIES. I already code it so that when for etc when meeting is selected for first dropdownlist, second dropdownlist will display the FAC_CODE column data that belongs to the FAC_TYPE column data.
The problem is whatever option that i choose for the FAC_CODE which belongs to any FAC_TYPE, it will always redirect to number1.aspx. I wan to make it so that, if I choose Meeting for the FAC_TYPE and whatever option for the FAC_CODE it will go to number1.aspx. If I choose Tutorial for the FAC_TYPE and whatever option for the FAC_CODE it will go to number2.aspx. If I choose Lecture for the FAC_TYPE and whatever option for the FAC_CODE it will go to number2.aspx.
My first dropdownlist name which is the FAC_TYPE field is called ddlFacilityType and my second dropdownlist name which is the FAC_CODE field is called ddlFacility. Both have autopostback ticked. So how to code in the ddlFacility_SelectedIndexChanged event? bumps up for this thread
public partial class MainMenu : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["projectConnectionString"].ToString(); // connection string
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct FAC_TYPE from FACILITIES", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds); // fill dataset
ddlFacilityType.DataTextField = ds.Tables[0].Columns["FAC_TYPE"].ToString(); // text field name of table dispalyed in dropdown
// to retrive specific textfield name
ddlFacilityType.DataSource = ds.Tables[0]; //assigning datasource to the dropdownlist
ddlFacilityType.DataBind(); //binding dropdownlist
ddlFacilityType.Items.Insert(0, new ListItem(" Select type", "0"));
}
ddlFacility.Items.Insert(0, new ListItem(" Select room", "0"));
}
protected void ddlFacilityType_SelectedIndexChanged(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["projectConnectionString"].ToString(); // connection string
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct FAC_CODE from FACILITIES where FAC_TYPE='" + ddlFacilityType.SelectedValue.ToString() + "'", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds); // fill dataset
ddlFacility.DataTextField = ds.Tables[0].Columns["FAC_CODE"].ToString(); // text field name of table dispalyed in dropdown
// to retrive specific textfield name
ddlFacility.DataSource = ds.Tables[0]; //assigning datasource to the dropdownlist
ddlFacility.DataBind(); //binding dropdownlist
ddlFacility.Items.Insert(0, new ListItem(" Select room", "0"));
}
protected void ddlFacility_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("number1.aspx");
}
}
You can do something like this in on ddlFacility_SelectedIndexChanged handler.
protected void ddlFacility_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddlFacilityType.SelectedItem.ToString() == "Meeting")
{
Response.Redirect("number1.aspx");
}
else if(ddlFacilityType.SelectedItem.ToString() == "Tutorial" || ddlFacilityType.SelectedItem.ToString()=="Lecture")
{
Response.Redirect("number2.aspx");
}
}
You can also do the same thing by the SelectedIndex property of the dropdownlist, in that case, the code would be something like
if(ddlFacilityType.SelectedIndex == 1) //Meeting is at index 1 of the ddlFacilityType dropdown
{
Response.Redirect("number1.aspx");
}

passing data to another page from nlevel menu

I have a multi level menu with asp.net c# that it gets its items from the database table. my table has items: menuID, menuname, description, parentID. my code is like below.
<asp:Menu ID="menuBar" runat="server" Orientation="Horizontal" Width="80%"
onmenuitemclick="menuBar_MenuItemClick" Height="28px">
</asp:Menu>
and the code behind is:
public void Connect()
{
con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["cnstring"].ConnectionString);
}
private void getMenu()
{
Connect();
con.Open();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string sql = "Select * from tbl_WebMenu";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
da.Fill(ds);
dt = ds.Tables[0];
DataRow[] drowpar = dt.Select("ParentID=" + 0);
foreach (DataRow dr in drowpar)
{
menuBar.Items.Add(new MenuItem(dr["MenuName"].ToString(), dr["MenuID"].ToString()));
}
foreach (DataRow dr in dt.Select("ParentID >" + 0))
{
MenuItem mnu = new MenuItem(dr["MenuName"].ToString(), dr["MenuID"].ToString());
mnu.Enabled = true;
}
con.Close();
}
I have a page that it's name is description.aspx. when clicking on the one of menu items, I want to redirect to description page and show the description of the selected menu item. I think I should use querystring, like on menuitem click: responce.redirect(description.aspx?ID=something) the problem is that I don't know how to get the ID of the selected item of menu and pass it to the description page.
please help me.
thank you
You can add parameters as Value when adding items to the menu and then retrieve these in on click event handler.
protected void menuBar_MenuItemClick(object sender, MenuEventArgs e)
{
Response.Redirect("SomePAge.aspx?ID=" + e.CommandArgument);
}

DropdownList DataSource

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.

How to implement editing Master/Detail records?

I have two tables.
tbl_Request(PKRequestID, RequestCode) and tbl_Personnel(PKPersonID, PerosnelName FKRequestID)
FKrfequestID is a foreign key to tbl_request. I have a grid view in Requests.aspx page that shows tbl_request records. There is a "New Item" button in this page too. When user clicks this button RequestInsert.aspx page opens. In this page user enters some data like RequestCode and hits the "Next" button and goes to Personel.aspx page which contains a gridview that shows the personnel who are related to the request. In this page user should define Personnel who are related to the request. When the whole process finishes user hits "save" button. Both tables will be update when user clicks on "save" button. How can I implement Personel.aspx page?
Here is the code for personnelaspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dttbl = new DataTable();
dttbl.Columns.Add("PKPersonID", System.Type.GetType("System.String"));
dttbl.Columns.Add("PerosnelName", System.Type.GetType("System.String"));
dttbl.Columns.Add("FKRequestID", System.Type.GetType("System.String"));
Session["MyDataTable"] = dttbl;
}
}
protected void btnok_Click(object sender, EventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
DataRow row1 = t.NewRow();
row1["PKPersonID"] = txtid.Text ;
row1["PerosnelName"] = txtname.Text;
row1["FKRequestID"] = Session["FKRequestID"];
t.Rows.Add(row1);
Session["MyDataTable"] = t;
GridView1.DataSource = t;
GridView1.DataBind();
}
protected void btnsave_Click(object sender, EventArgs e)
{
DataTable t2 = (DataTable)Session["MyDataTable"];
SqlConnection con = new SqlConnection("connection_string"
using (SqlCommand command = con.CreateCommand())
{
//Here you are inserting values to tbl_Request
if (con.State == 0)
con.Open();
command.CommandText = #"INSERT INTO tbl_Request (PKRequestID,RequestCode) VALUES (#PKRequestID,#RequestCode)";
command.Parameters.AddWithValue("#PKRequestID", Session["PKRequestID"]);
command.Parameters.AddWithValue("#RequestCode", Session["RequestCode"]);
command.ExecuteNonQuery();
}
foreach (DataRow row in t2.Rows)
{
//Here you are inserting values to tbl_Personnel
using (SqlCommand command2 = con.CreateCommand())
{
if (con.State == 0)
con.Open();
command2.CommandText = #"INSERT INTO tbl_Personnel (PerosnelName, FKRequestID) VALUES ( #PerosnelName, #FKRequestID)";
command2.Parameters.AddWithValue("#PerosnelName", txtname.Text);
command2.Parameters.AddWithValue("#FKRequestID", Session["PKRequestID"]);
command2.ExecuteNonQuery();
}
}
}
How can I implement edit mode? In this mode I want users be able to delete personnel or add them?
Ok. You need to use session to store the tbl_Request.PKRequestID of the record that is to be edited when user clicks Edit button. After that re direct the user to a new page Edit_Requests_Personnel.aspx where you can edit the records.

Categories

Resources