passing data to another page from nlevel menu - c#

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

Related

Gridview wont add another row on button click, it only adds one row and it updates that row only, how to fix this?

So I have a dropdown list that is being populate from database, the goal is to get the selected values from the dropdown list and put in the gridview. The problem is it only adds one row and only updates that row when I try to select new values from the dropdownlist.
I have tried doing Datarow row = dt.newrow() but not luck
Back End code of button click
string CS = ConfigurationManager.ConnectionStrings["POS_SystemConnectionString2"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Product_Details WHERE Model = '" + ddlModel.SelectedItem.Text + "' AND Price = '" +ddlPrice.SelectedItem.Text + "'", con);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
First image when I select values from dropdown list for first time
Second image is when I select new values from dropdown list but it updates previous table and does not add new row in gridview
On Add Button click you are retrieving new data from database and creating new datatable that's why you are loosing the previously selected data.
You need to maintain the previously retrieved data between two clicks on Add button.
You need to create a separate DataTable in aspx.cs and store it in the ViewState and add new row to that table on button click and re-bind it to the GridView.
You need to write following code to achieve this.
//This method will check if the table exist in the ViewState
//If table does not exist in ViewState, a new table will be created and stored in ViewState
private DataTable GetDataTable()
{
DataTable dt = ViewState["SelectedModels"] as DataTable;
if (dt == null)
{
dt = new DataTable();
dt.TableName = "ColorData";
dt.Columns.Add(new DataColumn("Model", typeof(string)));
dt.Columns.Add(new DataColumn("Price", typeof(string)));
ViewState["SelectedModels"] = dt;
}
return dt;
}
//This method will store DataTable to ViewState
private void SaveDataTable(DataTable dataTable)
{
ViewState["SelectedModels"] = dataTable;
}
//This method will get the data from the database, add it to the DataTable
//And it will re-bind the DataTable to the GridView and store the updated DataTable to ViewState
private void AddItemToList(string modelName, string price)
{
string CS = ConfigurationManager.ConnectionStrings["POS_SystemConnectionString2"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd =
new SqlCommand("SELECT * FROM Product_Details WHERE Model = #modelName AND Price = #price", con))
{
var modelParameter = new SqlParameter();
modelParameter.ParameterName = "#modelName";
modelParameter.Value = modelName;
cmd.Parameters.Add(modelParameter);
var priceParameter = new SqlParameter();
priceParameter.ParameterName = "#price";
priceParameter.Value = price;
cmd.Parameters.Add(priceParameter);
con.Open();
using (var sqlReader = cmd.ExecuteReader())
{
var dataTable = GetDataTable();
while (sqlReader.Read())
{
var dataRow = dataTable.NewRow();
//Hear I assume that Product_Details table has Model and Price columns
//So that sqlReader["Model"] and sqlReader["Price"] will not have any issue.
dataRow["Model"] = sqlReader["Model"];
dataRow["Price"] = sqlReader["Price"];
dataTable.Rows.Add(dataRow);
}
SaveDataTable(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
}
}
}
}
And now the Click Event Handler of the button should call the above method as following.
protected void bttnAdd_Click(object sender, EventArgs e)
{
AddItemToList(ddlModel.SelectedItem.Text, ddlPrice.SelectedItem.Text);
}
This should help you resolve your issue.

ASP.NET C# Creating checkboxes from DataTable

I am new to ASP.NET, but I need to create checkboxes from a query result. So far here is what I have.
In my code behind...I pull the query that I need and then create a DataTable from that result like so:
DataTable dtLocations = new DataTable();
dtLocations.Columns.Add("ID");
dtLocations.Columns.Add("VALUE");
// Pull locations and add to our datatable
string strConnection = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
using (SqlConnection dbConn = new SqlConnection(strConnection))
{
SqlDataAdapter dbAdapter = new SqlDataAdapter();
SqlCommand dbCommand = new SqlCommand();
dbConn.Open();
dbCommand.CommandText = #"SELECT location_id, location_desc FROM admin_locations WHERE enabled = 'Y'";
dbCommand.Connection = dbConn;
SqlDataReader dbReader = dbCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (dbReader.HasRows) {
while (dbReader.Read()) {
dtLocations.Rows.Add(new object[] { dbReader["location_id"].ToString(), dbReader["location_desc"].ToString() });
}
}
}
return dtLocations;
I then have a class level var defined as
public DataTable dtLocations = new DataTable();
which I populate using the method above in my Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!(IsPostBack))
{
dtLocations = createLocationsDataTable();
}
}
Then in my aspx file (not code behind) I'm doing this to try and create the checkboxes, which needless to say, does not work.
<% foreach (DataRow row in dtLocations.Rows) {%>
<asp:CheckBox ID="idLocationChk" runat="server" Value="<% Response.Write(row["ID"].ToString()); %>" />
<% } %>
Can someone show me how you're supposed to do this in ASP.NET c#? I'll also need to be able to get the value of any that are checked in my code behind when a button on the page is clicked.
When I try using a CheckBoxList like this it tells me I can not use codeblocks here.
<asp:CheckBoxList ID="message_locations" runat="server">
<% foreach (DataRow row in dtLocations.Rows) {%>
<asp:ListItem>TEST</asp:ListItem>
<% } %>
</asp:CheckBoxList>
You can bind a DataTable directly to a CheckBoxList
if (!IsPostBack)
{
CheckBoxList1.DataSource = dtLocations;
CheckBoxList1.DataTextField = "location_desc";
CheckBoxList1.DataValueField = "location_id";
CheckBoxList1.DataBind();
}

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");
}

How to implement IF statement using GridView

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

Categories

Resources