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
Related
I'm trying to make some columns readonly for not being able to edit them. I have tried a lot of solutions but none of them worked.I am using a gridview without datasource.( I have more tables and i'm displaying them using a dropdownlist).Anyway i want to edit just 2 column or one and i can't do this.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//// this function doesn't work
BoundField bound = GridView1.Columns[0] as BoundField;
bound.InsertVisible = false;
bound.ReadOnly = true;
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
((BoundField)GridView1.Columns[1]).ReadOnly = true;//this doesn't work too
GridViewRow row = GridView1.Rows[e.RowIndex];
string contract_ID = (row.Cells[2].Controls[0] as TextBox).Text;
string room_ID= (row.Cells[6].Controls[0] as TextBox).Text;
string query = "UPDATE CONTRACTE_INCHIRIERE SET ID_CAMERA='"+room_ID+"' WHERE ID_CONTRACT="+contract_ID;
Response.Write(query);
using (OracleCommand cmd = new OracleCommand(query,con))
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
//Reset the edit index.
GridView1.EditIndex = -1;
//Bind data to the GridView control.
SortingBindGrid();
}
Try:
GridView1.ReadOnly = true;
Or this for a single cell:
GridView1.Rows[rowIndex][colName].ReadOnly = true;
i have a 2 radiobutton on my webpage, they both have OnCheckedChanged event lik this
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
gender = "Male";
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
gender = "Female";
}
and i also have a dropdownlist which has OnSelectedIndexChanged event which populate an other dropdwonlist.
protected void Depid_SelectedIndexChanged(object sender, EventArgs e)
{
string id = Depiddrop.SelectedValue.ToString();
SqlCommand cmd = new SqlCommand("select StaffID, Name from Staff where Depid='" + id + "'", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Open();
empiddrop.DataSource = dt;
empiddrop.DataTextField = "Name";
empiddrop.DataValueField = "StaffID";
empiddrop.DataBind();
}
...the problem is that gender variable lose their value after postback (selectingitem from asp.net dropdownlist control). i also set the radiobutton property enableviewstate="true" but its not solving the problem.
..please help...and thanks
declare gender as static global variable
use something like
static string gender="";
use this as global variable
I want to make a gridview that when I select a row, its values will be populated to another gridview and text boxes, but I am encountering the error above. When I click the row in the GridView2, nothing is happening and an error in the sqladapter occurs. Please help me to fix this code..
Here is my code:
c#
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conn);
SqlCommand com = new SqlCommand("SELECT MRPNo, MRPType, MRPDate FROM MRP WHERE MRPNo = #mrpno",con);
com.Parameters.Add("#mrpno", GridView2.SelectedRow);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(com);
sda.Fill(dt);
DataRow row = dt.Rows[0];
txtMRPNo.Text = row["MRPNo"].ToString();
txtMRPDate.Text = row["MRPType"].ToString();
txtMRPDate.Text = row["MRPDate"].ToString();
GridView3.DataBind();
GridView1.DataBind();
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton selectButton = new LinkButton()
{
CommandName = "Select",
Text = e.Row.Cells[0].Text,
};
e.Row.Cells[0].Controls.Add(selectButton);
}
protected void GridView2_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.ToolTip = "Click to select row";
e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView2, "Select$" + e.Row.RowIndex);
}
}
}
You can not use GridView2.SelectedRow as an input to Parameters.Add(). Please refer to MSDN (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.selectedrow(v=vs.110).aspx) and you will see why.
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();
}
I'm working on datagridview in c# windows forms application and I'm loading the data from the database, now i want the user to be able to able to edit the cell value and save the value to the database, how to edit the cell value and how can i save the value to the database?
SqlConnection con = new SqlConnection("user id=sa;password=123;database=employee");
SqlDataAdapter da = new SqlDataAdapter("select * from UserReg", con);
DataSet ds = new DataSet();
da.Fill(ds, "p");
dataGridView1.DataSource = ds.Tables["p"];
One of the way to update a database with DataGridView is using of DataGridView's events:
DataGridView.CellBeginEdit
DataGridView.CellValidating
DataGridView.CellEndEdit
Let say: private DataGridView dgv;
Add handlers of events
dgv.CellBeginEdit += dgv_CellBeginEdit;
dgv.CellValidating += dgv_CellValidating;
dgv.CellEndEdit += dgv_CellEndEdit;
private void dgv_CellBeginEdit(Object sender, DataGridViewCellCancelEventArgs e)
{
//Here we save a current value of cell to some variable, that later we can compare with a new value
//For example using of dgv.Tag property
if(e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
this.dgv.Tag = this.dgv.CurrentCell.Value;
//Or cast sender to DataGridView variable-> than this handler can be used in another datagridview
}
}
private void dgv_CellValidating(Object sender, DataGridViewCellValidatingEventArgs e)
{
//Here you can add all kind of checks for new value
//For exapmle simple compare with old value and check for be more than 0
if(this.dgv.Tag = this.dgv.CurrentCell.Value)
e.Cancel = true; //Cancel changes of current cell
//For example used Integer check
int32 iTemp;
if (Int32.TryParse(this.dgv.CurrentCell.Value, iTemp) = True && iTemp > 0)
{
//value is ok
}
else
{
e.Cancel = True;
}
}
Private Sub dgvtest1_CellEndEdit(Object sender, DataGridViewCellEventArgs e)
{
//Because CellEndEdit event occurs after CellValidating event(if not cancelled)
//Here you can update new value to database
}
Try to do this:
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
//after you've filled your ds, on event above try something like this
try
{
da.Update(ds);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I used OleDb but you can use SQL. Here is the code I usually use for the same.
OleDbCommand sCommand;
OleDbDataAdapter sAdapter;
OleDbCommandBuilder sBuilder;
OleDbConnection connection;
DataSet sDs;
DataTable sTable;
string myMode = "";
private void BtnLoad_Click(object sender, EventArgs e)
{
string query = "SELECT * FROM [Table]";
connection = new OleDbConnection(connectionString);
connection.Open();
sCommand = new OleDbCommand(query, connection);
sAdapter = new OleDbDataAdapter(sCommand);
sBuilder = new OleDbCommandBuilder(sAdapter);
sDs = new DataSet();
sAdapter.Fill(sDs, "Table");
sTable = sDs.Tables["Table"];
connection.Close();
DataGrid.DataSource = sTable;
DataGrid.ReadOnly = true;
DataGrid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
private void BtnAdd_Click(object sender, EventArgs e)
{
DataGrid.ReadOnly = false;
myMode = "add";
}
private void BtnEdit_Click(object sender, EventArgs e)
{
DataGrid.ReadOnly = false;
myMode = "edit";
}
private void BtnDelete_Click(object sender, EventArgs e)
{
myMode = "";
if (MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
DataGrid.Rows.RemoveAt(DataGrid.SelectedRows[0].Index);
sAdapter.Update(sTable);
}
}
private void BtnSave_Click(object sender, EventArgs e)
{
if (myMode == "add")
{
sAdapter.Update(sTable);
MessageBox.Show("Prices Are Successfully Added.", "Saved.", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
else if (myMode == "edit")
{
string query = "UPDATE Table_Name SET " +
"Column1 = '" + DataGrid.SelectedRows[0].Cells[0].Value.ToString() + "' ," +
"Column2 = " + DataGrid.SelecteddRows[0].Cells[1].Value.ToString() + ", " +
"WHERE CONDITION";
connection = new OleDbConnection(connectionString);
connection.Open();
sCommand = new OleDbCommand(query, connection);
sAdapter = new OleDbDataAdapter(sCommand);
sBuilder = new OleDbCommandBuilder(sAdapter);
sDs = new DataSet();
sAdapter.Fill(sDs, "Table");
sTable = sDs.Tables["Table"];
connection.Close();
DataGrid.DataSource = sTable;
DataGrid.ReadOnly = true;
}
}
Have a look at the DataGridView Events list. You need to subscribe to the appropriate event, and handle it accordingly. Namely, you're interested in DataGridView.CellValueChanged.
dataGridView1.CellValueChanged += ValueChangedHandler;
private void ValueChangedHandler(object sender, DataGridViewCellEventArgs e) {
// do what is appropriate here.
}
Add this line of code to enable editing on datagridview
dtg.EditMode = DataGridViewEditMode.EditOnKeystroke;
Then use below event
private void dtg_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex > -1 && e.RowIndex > -1)
{
dtg.ReadOnly = false;
}
}
The above two events will enable editing in datagridview.
Then use below event to save the updated data back to db.
private void dtg_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
}