How to insert dropdownlist value, text box value and gridviews selected row together? - asp.net

How to insert dropdownlist value, text box value and gridviews selected row together?
Also attached the screenshot of the data insert:
enter image description here
enter image description here
enter image description here

I tend to prefer a add button that adds a row to the grid, and THEN you let the user edit the one row.
However, assuming you have those text boxes at the top of the screen, enter data, and then click a button to add to the database, and then re-fresh the GV?
I also don't see some button in the top area to add the data?
so, say a button added to the top area?
then this would add the row to the database:
protected void Button3_Click(object sender, EventArgs e)
{
string strSQL =
"INSERT INTO MyTable (Session, Class, Section, Term, Subject, HighestMark) " +
"VALUES (#Session, #Class, #Seciton, #Term, #Subject, #HighestMark)";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL,conn))
{
conn.Open();
cmdSQL.Parameters.Add("#Session", SqlDbType.Int).Value = DropSession.selecteditem.value;
cmdSQL.Parameters.Add("#Class", SqlDbType.Int).Value = DropClass.selecteditem.value;
cmdSQL.Parameters.Add("#Section", SqlDbType.Int).Value = DropSection.selecteditem.value;
cmdSQL.Parameters.Add("#Term", SqlDbType.Int).Value = DropTerm.selecteditem.value;
cmdSQL.Parameters.Add("#Subject", SqlDbType.Int).Value = DropSubject.selecteditem.value;
cmdSQL.Parameters.Add("#HighestMark", SqlDbType.Int).Value = HighestMark.Text;
cmdSQL.ExecuteNonQuery();
}
}
ReloadGrid(); // call routine to refresh the grid.
}
Edit: Adding the rows to a new table
Ok, so we are to take the top values, and then process each row of the grid, and take the ones with a check box and "insert" this data into a new table.
Ok, so the code will look like this:
protected void Button1_Click(object sender, EventArgs e)
{
string strSQL = "SELECT * FROM tblHotelsA WHERE ID = 0";
DataTable rstData = MyRst(strSQL);
foreach (GridViewRow gRow in GHotels.Rows)
{
CheckBox ckChecked = gRow.FindControl("ckSelected") as CheckBox;
if (ckChecked.Checked)
{
// this row was checked - add a new row
DataRow MyNewRow = rstData.NewRow();
MyNewRow["HotelName"] = txtHOtelName.Text; // exmaple control
MyNewRow["City"] = txtCity.Text; // example control above grid
// values from grid row
// tempalted columns, we use find control
MyNewRow["FirstName"] = (gRow.FindControl("txtFirstName") as TextBox).Text;
MyNewRow["LastName"] = (gRow.FindControl("txtLastName") as TextBox).Text;
// if data bound column, then we use cells collection
MyNewRow["FavorateFood"] = gRow.Cells[5];
// etc. etc.
rstData.Rows.Add(MyNewRow);
}
}
// done adding to table, write/save back to database.
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
cmdSQL.Connection.Open();
da.Update(rstData);
}
}
}
I also had this helper routine - I often use it all over the palce:
public DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
So, the concept here?
I pulled a blank row (SELECT * from table where ID = 0).
This gets me the database structure - and thus avoids a BOATLOAD of parameters in the sql.
this approach ALSO allows me to add a row to the table, and add "many" rows. And then execute ONE update to the database to write out (save) all the rows in one shot. So, this again reduced quite a bit of messy code.

Related

Set focus on the repeated row data while typing duplicate value

I have a gridview in asp.net, in which I am inserting datas. When I insert repeated value then it will show item repeated. Now I need to show after the item repeated alert message the cursor will focus on the row value contain the item which is repeated. If my data table already contain code C1, then I again type c1 for insert then the cursor will focus on the row which contain c1 in gridview. Here is my code
protected void Button15_Click(object sender, EventArgs e)
{
Control control = null;
if (GridView1.FooterRow != null)
{
control = GridView1.FooterRow;
}
else
{
control = GridView1.Controls[0].Controls[0];
}
string Code = (control.FindControl("txtcode") as TextBox).Text;
string txtno= (control.FindControl("txtno") as TextBox).Text;
using (SqlConnection con = new SqlConnection("Data Source=XXXXXX;Initial Catalog=XXXXXX;User ID=XXXX;Password=XXXXXX"))
{
using (SqlCommand cmd = new SqlCommand())
{
DataTable dt = new DataTable();
SqlDataAdapter da1;
da1 = new SqlDataAdapter("select code from tbltmp where code='" + Code + "' ", con);
da1.Fill(dt);
if (dt.Rows.Count > 0)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Item Repeated');", true);
(control.FindControl("txtcode") as TextBox).Focus();
}
else
{
(control.FindControl("txtno") as TextBox).Focus();
}
}
}
}
set focus on the textbox as textbox1.focus in button event of repeated row checking

store selected grid view value into database

I've a gridview in which a radiobutton is used to select a particular row of data. Now I need to save radio button selected row into database. How do I achieve this? I'm not using JQuery or Ajax, my entire coding is done on ASP.NET
I didn't got your problem correctly,But the ideal methodology is to use Check box instead of Radio button will be far better for your coding purpose.
The below code is a demo for inserting the values into the database from a grid view where in the particular rows will be inserted which has been checked.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConnectionstring"].ToString());
SqlCommand cmd = new SqlCommand();
string active = "N";
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
string A = GridView1.Rows[i].Cells[0].Text;
string B = GridView1.Rows[i].Cells[1].Text;
GridViewRow row = GridView1.Rows[i];
CheckBox Ckbox = (CheckBox)row.FindControl("CheckBox1");
if (Ckbox.Checked == true)
{
cn.Open();
cmd.CommandText = "Insert into table_name(A,B) values (#A,#B)";
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#A", A);
cmd.Parameters.AddWithValue("#B", B);
cmd.ExecuteNonQuery();
cn.Close();
}
}
Hope this will be helpful for you.
Easy
Search through GridRows
FindControl radio button on each row.
Check that button is Checked or not.
and now try it.

binding dropdownlist values to textbox

When the user selects an order ID, the rest of the order information is displayed in label(s). Display the following: employee ID, order date, freight, shipped name, and country. This functionality should be implemented using direct data access programmatically.
Edit: code example and additional explanation.
String CS = onfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionStr‌​ing;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT OrderID FROM Orders", con);
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "OrderID";
DropDownList1.DataValueField = "OrderID";
DropDownList1.DataBind();
Label1.Text = Convert.ToString(DropDownList1.SelectedItem.Text);
}
What I want is the other fields which are there in orders table to be displayed when a value is selected in the dropdownlist.
Can you make datatable from the SQL Query result, and then add items to dropdownlist from ID column. When you then select an item from DDL, you show the info where the row from datatable match the selected orderID.
I can write code if you want it isn't cleared what I'm meaning.
UPDATE: with code
var ds = new DataSet();
using (var conn = new SqlConnection(connection))
{
conn.Open();
var command = new SqlCommand("Your SQL Query", conn);
var adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
conn.Close();
} //Now you have a dataset, with one table that matches your query result.
//And now we can use a foreach loop to add every OrderID to dropdownlis
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
DDLname.Items.Add(dr[0].ToString());
}
}
//onSelectedValue event
string orderID = DDLname.Text.toString();
Label1.Text = orderID;
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
if(dr[0].toString().equals(orderID))
{
Label2.text = dr[1].toString();
Label3.text = dr[2].toString();
etc....
}
}
}
As you labelled your question with ASP.Net, I assume that this is part of an ASP.Net Webforms application. This means that the drop down list will be inside a web page in a browser. Not clear to me is whether you want the label to be displayed immediately when the user select the item, or only after a post to the server.
In the first case, you'll need javascript and probably something like Ajax or JSON to get the data you want to display for the selected item. In the second case, you could add an event handler for the SelectedIndex_Changed Event of your drop down list. This handler should do something like this:
string CS = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT OrderID FROM Orders WHERE OrderId = #OrderId", con);
cmd.Parameters.AddWithValue("#OrderId", DropDownList1.SelectedItem.Value);
con.Open();
if (reader.Read())
{
SqlDataReader reader = cmd.ExecuteReader();
Label1.Text = String.Format("Employee ID: {0}, order date: {1}, freight: {2}, shipped name: {3}, and country {4}."
, reader["employeeid"].ToString()
, reader["orderdate"].ToString()
, reader["freight"].ToString()
, reader["shipname"].ToString()
, reader["shipcountry"].ToString());
}
}

Gridview from button click inside a popup window

I have a text box with event name and two calendar controls to get the date and a button to display a gridview.
I need to display the grid with the details like eventname start date and end date from the database..
My code is .aspx.cs
protected void lnbtnSearch_OnClick(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=CTSINDLFVMOSS;Initial Catalog=DB_CGTPO_DEVE;Persist Security Info=True;User ID=*****;Password=*****");
SqlDataAdapter adapter = new SqlDataAdapter("select EventId,EventName,StartDate,EndDate,Tactics,Perct_VolLift,Perct_ROI from TableNamewhere (( EventName='" + textfield3 + "') and (StartDate= StartDate) and ( EndDate= EndDate))", conn);
DataSet ds = new DataSet();
adapter.Fill(ds);
grdEventDetails.DataSource = ds;
grdEventDetails.
}
set grdEventDetails.AutoGenerateColumns = true;
add grdEventDetails.DataBind();
but it will look ugly (especially date fields) if you don't define the columns manually.

Finding the item in selecteditemchanging event

In listview im showing product information .On each row there is one select button on each row in itemTemplate .
if user click this button i want which bookid is clicked in selectedindexchanging event.
i bound listview like following
string str = "SELECT BookName,BookPrice, Description, bookid FROM productinfo Where Categoryid ='" + Request.QueryString["CategoryId"] + "'";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(str, conn);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
lstvwShopItems.DataSource = dt;
lstvwShopItems.DataBind();
Please give solution?
in order to get a certain column when selecting a row you need to fill the property datakeynames with the property of your choice.
msdn
getting the value of the property:
void lstvwShopItems_SelectedIndexChanged(Object sender, EventArgs e)
{
string value = lstvwShopItems.SelectedValue;
}
don't forget to set the OnSelectedIndexChanged on your listview to this method in the codebehind..

Resources