how to get DataValue of dropdownlist in ASP.NET C# - c#

i have a problem as subject said.
i have a Table courses in sql server Fields are courseID and course.
what i want is list the course in dopdown and i succeeeded but what i'm not able to do is when i select a course from dropdown list, a courseID should be selected in HiddenField/textbox/label
how to do that
here is a code i tried::
protected void Page_Load(object sender, EventArgs e)
{
string select = "select * from courses";
DropDownList1.Items.Add("-- Select Course --");
DropDownList1.SelectedIndex = 0;
DataTable dt = con.select_command(select);
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList1.Items.Add(dt.Rows[i][1].ToString());
DropDownList1.DataValueField = dt.Rows[i][0].ToString();
DropDownList1.DataTextField = dt.Rows[i][1].ToString();
}
}
in dropdownlist i'm getting values in Page Load method
i also tried dropdownlist_selectedindex change method too to select courseID
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
LLabel1.Text = DropDownList1.SelectedValue.ToString();
}
what i'm doing wrong ???

Place a block of if (!IsPostBack) before you update the dropdown in your page_load
The problem is that your code will re-populate the dropdown menu after the DropDownList1_SelectedIndexChanged event will be triggred.
That will make a post request to the server and he will run the DropDownList1_SelectedIndexChanged function attached to the IndexChange event and then page_load
because the page suppose to be loaded again
and will result in a new selected value that will not be what you expect it to be.
One more thing: use string identifiers when getting a value from a Row of a DataTable the code will be much more friendly that way. (Readability is very important...)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string select = "select * from courses";
DropDownList1.Items.Add("-- Select Course --");
DropDownList1.SelectedIndex = 0;
DataTable dt = con.select_command(select);
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList1.Items.Add(dt.Rows[i]["CourseName"].ToString());
DropDownList1.DataValueField = dt.Rows[i]["CourseID"].ToString();
DropDownList1.DataTextField = dt.Rows[i]["CourseName"].ToString();
}
}
}

try this
above code you manually add item to dropdownlist so you have to add datavalue as well as
protected void Page_Load(object sender, EventArgs e)
{
if(!Ispostback)
{
string select = "select * from courses";
DropDownList1.Items.Add("-- Select Course --","0");
DataTable dt = con.select_command(select);
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList1.Items.Add(new listitem(dt.Rows[i][1].ToString(),dt.Rows[i][0].ToString();
));
}
DropDownList1.SelectedIndex = 0;
}
}
and your select index change event
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
LLabel1.Text = DropDownList1.SelectedValue.ToString();
}

Related

How to edit image from gridview with some other fields in c#?

I m new to .net.
code-behind:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (e.CommandName == "EditRow")
{
GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
int index = gr.RowIndex;
hiddenfield.Value = index.ToString();
Textid.Text = gr.Cells[0].Text;
Textusername.Text = gr.Cells[1].Text;
Textclass.Text = gr.Cells[2].Text;
Textsection.Text = gr.Cells[3].Text;
Textaddress.Text = gr.Cells[4].Text;
}
else if (e.CommandName == "Deleterow")
{
SqlCommand com = new SqlCommand("StoredProcedure4", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#ID", Convert.ToInt32(e.CommandArgument));
var id = Int32.Parse(e.CommandArgument.ToString());
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
}
protected void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
{
int index = GridView1.SelectedIndex;
hiddenfield.Value = index.ToString();
}
When i edit the row, all fields are displayed in text box expect image filed.
Because recently i added image field, and i don't know how to edit and update image.
Here is my output screenshot
May i know, how to know about this problem?
Any help would be highly appreciated.
Thanks,
in the edit mode template, add instead of the image control a text box with the url as text property or add a fileUpload control

GridView RowUpdating not getting new data

When trying to update GridView data, it successfully runs, but it gets the old data instead of the data you type in the textboxes.
This is what I have:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
string phone = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
string email = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
int contactId = Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text);
objLogic.UpdateContact(name, phone, email, contactId); //passes values to SQL to update database
GridView1.EditIndex = -1;
GridView1.DataBind();
}
and
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
and
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataSource = objLogic.LoadClient();
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "clientId";
DropDownList1.DataBind();
}
GridView1.DataSource = objLogic.LoadContacts(Convert.ToInt16(DropDownList1.SelectedValue));
GridView1.DataBind();
For example, the current data is:
name: Blake, phone: 123-234-3456, email: test#test.com, contactId: 22
I type in new data:
name: John, phone: 555-555-5555, email: test2#test2.com, contactId: 22
Data that ends up in the database:
name: Blake, phone: 123-234-3456, email: test#test.com, contactId: 22
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataSource = objLogic.LoadClient();
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "clientId";
DropDownList1.DataBind();
BindGrid();
}
}
protected void BindGrid()
{
GridView1.DataSource = objLogic.LoadContacts(Convert.ToInt16(DropDownList1.SelectedValue));
GridView1.DataBind();
}
Every time the page posts back you are rebinding the grid. Move the binding of the grid into a separate function. After you do the row updating, rebind the grid.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
string phone = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
string email = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
int contactId = Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text);
objLogic.UpdateContact(name, phone, email, contactId); //passes values to SQL to update database
GridView1.EditIndex = -1;
BindGrid();
}
When you edit you must call BindGrid too.
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
//GridView1.DataBind(); this is meaningless, you have not set a DataSource
BindGrid();
}
When you raise the RowUpdating event your basically getting the values BEFORE the GridView updates the row. This is basically so you can cancel the update operation. To get what you've type in I think you need to get the new values (the Dictionary e.NewValues() in your case).
In your case you can use it something like this (assuming name, phone and email are what they're called in your gridview):
foreach(DictionaryEntry de in e.NewValues())
{
string name = de.FirstOrDefault(x => x.Key == "name").Value;
string phone = de.FirstOrDefault(x => x.Key == "phone").Value;
string email = de.FirstOrDefault(x => x.Key == "email").Value;
}
NOTE: If you're simply using this to get the values typed in to update your database then you're better of binding the datagrid and use the value after that to ensure you definitely have the same values in the datagrid as to what you put into the database. Alternatively, use the RowUpdated event instead of the RowUpdating event.
The most prevalent reason is that we usually forgot to check the postbacks in the Page Load event.
check the post-back, then the problem will be removed.
if (! IsPostBack)
{
readData();
...
}
Prokzy I have just your example on my side and doing something like this worked fine for me. notice the DataSource portion. I have a DataSet instantiated as aDataSet btw
protected void GridView1_GridViewPageEventArgs e(object sender, GridViewPageEventArgs e)
{
GridView1.EditIndex = e.NewPageIndex;
GridView1.DataSource = null;
GridView1.DataSource = aDataset;
GridView1.DataBind();
}
You need to call LoadContacts again and reassign GridView1.DataSource after the database is updated. Currently, the DataSource is not being updated - and is just using the collection that was retrieved prior to the row update.

move values from one column in gridview to another column in the same gridview

ID sum payed
1 354 200
1 2345 23435
I have this gridview2, comes from a gridview1 with selecting rows with checkbox.
I want to move the values from sum to payd, so payed gets the values from sum and then sum became empty. Please help me i'm new to this.
Thanks :)
namespace WebApplication5
{
public partial class Presmetuvanje : System.Web.UI.Page
{
public int #UserID;
SqlConnection sqlConn = new SqlConnection(Web.GetConfigValue("proekt1"));
//private DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlConn = new SqlConnection(Web.GetConfigValue("proekt1"));
if (Web.IsMemberSession)
{
Response.Write("Welcome" + " " + Web.SessionUser.Naziv);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
String Oznacheni = "";
SqlConnection sqlConn = new SqlConnection(Web.GetConfigValue("proekt1"));
CheckBox ch;
foreach (GridViewRow row in GridView1.Rows)
{
ch = (CheckBox)row.FindControl("CheckBox1");
if (ch.Checked == true)
{
String pom = row.Cells[0].Text;
if (Oznacheni.Length > 0) pom = ", " + pom;
Oznacheni += pom;
}
}
if (Oznacheni.Length < 1) Oznacheni = "-1";
SqlDataSource2.SelectCommand = " SELECT * FROM fakturis WHERE fakturaID IN (" + Oznacheni + ")";
SqlDataSource2.DataBind();
GridView2.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
Web.SessionUser = null;
Web.IsMemberSession = false;
Response.Redirect("Login.aspx");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void Button3_Click(object sender, EventArgs e)
{
int sum = 0;
for (int i = 0; i < GridView2.Rows.Count; i++)
{
sum += int.Parse(GridView2.Rows[i].Cells[7].Text);
}
Label1.Text = "Platenata suma iznesuva "+sum.ToString() +" denari";
}
}
}
After this Button3_Click i want to add new method who will put the values from sum to payd
and then sum became empty.

How to take the value from a column while hover the mouse

I have 2 grids in a form. One grid is filled with some Students info. And I want that when I put the Mouse over the dataGridview1, to show the other gridview like a Popup or something like that, and populate the other datagridview with informatin based on the Name column.
I did the part where the grid shows as a popup and follows the mouse. Also when it leaves the grid it will disappear:
private void dataGridView1_MouseHover(object sender, EventArgs e)
{
SqlDataAdapter da2;
DataTable dt2 = new DataTable();
da2 = new SqlDataAdapter("SELECT ID, Name, Surname, City"+
"FROM tblStudents2" +
"WHERE Name = **what to write here**", con);
da2.Fill(dt2);
dataGridView2.DataSource = dt2;
}
private void dataGridView1_MouseLeave(object sender, EventArgs e)
{
dataGridView2.Visible = false;
}
private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
dataGridView2.Visible = true;
dataGridView2.Location = new Point(MousePosition.X-100, MousePosition.Y-100);
}
I just want to ask you, what to write i the SQL Statement, at the part: WHERE Name='____' ??
I want that when the Mous is over the first Row, to take the Name (column index 1) and populate the other datagrid.
I hope you understand me :(
****EDITED
Here is my code after going through the Code Of Ehsan... It workes almost. The problem is it doesn't Repopulate the grid after moving the mouse to the next row!! Butif I leave the DataGrid, and put the mouse to the other Row, it shows me the ifnormation of this row. How to make something lik a refresh grid after moving the mouse to the next row??
public void LoadGridi2()
{
SqlDataAdapter da2;
DataTable dt2 = new DataTable();
da2 = new SqlDataAdapter("SELECT ID, Name, Surname, City FROM tblMentori WHERE Name = '" + dataGridView1.Rows[row.Index].Cells[1].Value.ToString() + "'", con);
da2.Fill(dt2);
dataGridView2.DataSource = dt2;
}
private void dataGridView1_MouseHover(object sender, EventArgs e)
{
LoadGridi2();
}
private void dataGridView1_MouseLeave(object sender, EventArgs e)
{
dataGridView2.Visible = false;
}
DataGridViewRow row;
private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
dataGridView2.Visible = true;
dataGridView2.Location = new Point(MousePosition.X - 100, MousePosition.Y - 100);
}
private void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0)
{
row = (DataGridViewRow)dataGridView1.Rows[e.RowIndex];
}
}
You should do this. Bind to the CellMouseMove event of grid.
private void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = DataGridViewRow)dataGridView1.Rows[e.RowIndex];
SqlDataAdapter da2;
DataTable dt2 = new DataTable();
da2 = new SqlDataAdapter("SELECT ID, Name, Surname, City FROM tblStudents2 WHERE Name = '" + row["Name"].Value.ToString()+ "'", con);
da2.Fill(dt2);
dataGridView2.DataSource = dt2;
}
}
and
e.RowIndex
is the index you are looking for
Use CellMouseMove event. You can get item which is bound to current row (e.g. some Person instance):
void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex < 0)
return;
DataGridView grid = (DataGridView)sender;
var person = (Person)grid.Rows[e.RowIndex].DataBoundItem;
var name = person.Name;
}
Here is full code (I use label control for simplicity):
// this field used to avoid loading data which you already have
private Person currentPerson;
void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex < 0)
{
HidePersonDetails();
return;
}
DataGridView grid = (DataGridView)sender;
var person = grid.Rows[e.RowIndex].DataBoundItem as Person;
if (person == null)
{
HidePersonDetails();
return;
}
var rectangle = grid.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
var cellLocation = rectangle.Location;
var detailsLocation = new Point(e.X + cellLocation.X,
e.Y + cellLocation.Y + rectangle.Height);
ShowPersonDetails(person, detailsLocation);
}
private void dataGridView1_MouseLeave(object sender, EventArgs e)
{
HidePersonDetails();
}
private void ShowPersonDetails(Person person, Point location)
{
if (currentPerson != person)
{
// get data from SQL server
// set datasource of your details grid
currentPerson = person;
}
label1.Text = person.Name;
label1.Location = location;
label1.Show();
}
private void HidePersonDetails()
{
label1.Hide();
}

asp.net gridview dynamically binding

i have a GridView,
<asp:GridView ID="managerList" runat="server" DataSourceID="SqlDataSource2">
in the code behind,
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource2.SelectCommand = "select * from manager";
managerList.AllowPaging = true;
}
when i load the page, it works fine, the paging works fine, too.
Then i want to get the subset of the list by click on a search button:
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlDataSource2.SelectCommand = "select * from manager where age > 30";
managerList.DataBind();
}
it works fine, give me the subset of the list.
However, when i click on "next page", it gives me the whole list, page #2. I know it's because it sends a postback, and it bind the original select command. But how can i do to give me the subset of the list when i click on "next page"?
Thank you!
UPDATES:
if i change the code into this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
SqlDataSource2.SelectCommand = "select * from manager";
managerList.AllowPaging = true;
}
}
it gives me an empty list when i click on "next page".
it might be tempted to add IsPostBack, but this not work.
Add the NewPageIndex code in the PageIndexChanging event:
managerList.PageIndex = e.NewPageIndex;
bindgrid();
Below might help you
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDataSource2.SelectCommand = "select * from manager";
managerList.AllowPaging = true;
}
}
You need to put your code under !IsPostBack() in the page_load event. like...
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
SqlDataSource2.SelectCommand = "select * from manager";
managerList.AllowPaging = true;
}
}
Reason: Whenever you hit the Next button, your page load event is called before the PageIndexChanging Event handler of Gridview.
Page_Load fires every time the page is loaded, including postbacks, so your select statement is getting reset. Try setting a viewstate value to keep your select statement.
Store the most recent SQL Query in a global static string and then use the following code.
static String previousSQL_Query;
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
SqlDataSource2.SelectCommand = previousSQL_Query;
}
else
{
SqlDataSource2.SelectCommand = "select * from manager";
managerList.AllowPaging = true;
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlDataSource2.SelectCommand = "select * from manager where age > 30";
previousSQL_Query = SqlDataSource2.SelectCommand;
managerList.DataBind();
}

Categories

Resources