DropDownList Selection instead of a TextBox in AutoGenerated Gridview Columns - c#

I bind a Gridview read from my Oracle Database. I have an edit, and delete button. My aim is that when I have a certain table selected and I press my edit button, I replace the first two textboxes with dropdownlists so I restrict what the user can pick in order to run my SQL statement to my database with the selectedvalue in the dropdownlist instead of the textbox value. I have no TemplateFields to reference my columns in the Gridview because they are autogenerated. When I press my update button on my Gridview, it doesn't update from the DropDownList selected value but instead the text value which was in the Gridview. This is a snippet of my code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
//Locate the textboxs I want to replace
TextBox disableJOBRun = e.Row.Cells[2].Controls[0] as TextBox;
TextBox disableAction = e.Row.Cells[3].Controls[0] as TextBox;
//Create the new DropDownLists
DropDownList JobRunSelection = new DropDownList();
DropDownList ActionSelection = new DropDownList();
//Bind the DropDownLists
JobRunSelection.DataSource = ds;
JobRunSelection.DataValueField = "JOBNAME";
JobRunSelection.DataBind();
ActionSelection.DataSource = dsTwo;
ActionSelection.DataValueField = "NAME";
ActionSelection.DataBind();
con.Close();
//Change Text of Textbox
JobRunSelection.SelectedValue = disableJOBRun.Text;
ActionSelection.SelectedValue = disableAction.Text;
//Add the DropdownsLists to the Gridview
e.Row.Cells[2].Controls.Add(JobRunSelection);
e.Row.Cells[3].Controls.Add(ActionSelection);
JobRunSelection.Attributes.Add("runat", "server");
ActionSelection.Attributes.Add("runat", "server");
JobRunSelection.ID = "DropDownJobRunSelection";
ActionSelection.ID = "DropDownActionSelection";
//Hide Textboxes
disableJOBRun.Visible = false;
disableAction.Visible = false;
}
}
protected void GridView1_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
//Get Connection to database
GridViewRow row = GridView1.Rows[e.RowIndex];
String newJobID = ((TextBox)(row.Cells[2].Controls[0])).Text;
String newAction = ((TextBox)(row.Cells[3].Controls[0])).Text;
//Update Table
cmd.CommandText = "UPDATE " + SelectedTable + " SET JOBID = :param2, WHERE " + KeyName + " = " + "'" + KeyValue + "'";
cmd.Parameters.Add(":param2", newJobID);
cmd.Parameters.Add(":param3", newAction);
Perhaps Page_Load resets the text back to its original? If so, how would I go about implementing my DropDownLists? Thanks for any help and I will post any more code necessary.

I solved my problem, I had switched the order of the variables of the Dropdownlist selected value and the text box text. Once I switched them, my text boxes changed their values.

Related

How to access to current DataGridView dynamically

I'll try to be clear :)
I am creating new DataGridView dynamically thanks to a button.
It works fine, but then I want to be able to change the value of one cell of a DataGridView and update my database.
The problem is that I do not find how to get the current focused DataGridView.
I tried to play with the code in this link, I get the name of the current DataGridView.
But I don't think I can manipulate a control as a DataGridView.
Here is my function :
private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
DataGridView datagridcell = new DataGridView();
string codearticle = "'" + CodeArticle0.Text + "'";
string division = "'" + Division0.Text + "'";
string colonne = datagridcell.Columns[e.ColumnIndex].HeaderText;
string valeur = sender.ToString();
string Ligne = datagridcell.Rows[0].Cells[3].ToString();
Controller.ControllerMenuPrincipal.updateQALigneFab(codearticle, division,
colonne, valeur, Ligne);
}
Instead of this :
DataGridView datagridcell = new DataGridView();
I want to access the current/focused datagridview
I do not know if it is possible, I am a noob in winforms.
thanks for the help
Solution
As Reza Aghaei said,
" If you attached dataGridView_CellValueChanged to CellValueChanged of yourdynamic grids, then the sender parameter is the DataGridView which the event is fired for it. So you can get the sender DataGridView this way: var grid = (DataGridView)sender;. – Reza Aghaei"
so i just replaced this line :
DataGridView datagridcell = new DataGridView();
by this one:
var grid = (DataGridView)sender;
so i can use "grid" variable to manipulate my current datagridview
final code looks like that :
private void dataGridView13_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
var grid = (DataGridView)sender; //get current datagridview
string codearticle = "'" + CodeArticle0.Text + "'";
string division = "'" + Division0.Text + "'";
string colonne = grid.Columns[e.ColumnIndex].HeaderText; //get column headertext of current cell
string valeur = grid[e.ColumnIndex, e.RowIndex].Value.ToString(); //get new value of current cell
string Ligne = grid[3, 0].Value.ToString();
Controller.ControllerMenuPrincipal.updateQALigneFab(codearticle, division, colonne, valeur, Ligne); //calling stored procedure to update my table
}

How to stop MessageBox repetition when LinkLabel in DataGridView column is clicked

1.This is My Form:
2.Message pops-up when LinkLabel in DataGridView is clicked:
private void button3_Click(object sender, EventArgs e)
{
dataGridView1.Columns.Clear();
con.Open();
SqlDataAdapter da
= new SqlDataAdapter("SELECT casetype, caseno, year from cases where casetype = '"
+ textBox2.Text + "'", con);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
LinkLabel link = new LinkLabel();
link.Text = "More Information !";
DataGridViewLinkColumn col2 = new DataGridViewLinkColumn();
col2.Name = "column2";
col2.HeaderText = "Information";
dataGridView1.Columns.Add(col2);
dataGridView1.CellContentClick +=
new DataGridViewCellEventHandler(dataGridView1_CellContentClick_1);
for (int i = 0; i < dt.Rows.Count; i++)
{
dataGridView1.Rows[i].Cells[3].Value = link.Text;
}
}
private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
//dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString()
con.Open();
SqlDataAdapter da
= new SqlDataAdapter("SELECT * FROM cases WHERE caseno = '"
+ dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString()
+ "'", con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
DateTime current = DateTime.Now;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
MessageBox.Show("1.Case Type = "
+ ds.Tables[0].Rows[i]["casetype"].ToString()
+ "\n\n2.Case No = " + ds.Tables[0].Rows[i]["caseno"].ToString()
+ "\n\n3.Case Year = " + ds.Tables[0].Rows[i]["year"].ToString()
+ "\n\n4.Case Name = " + ds.Tables[0].Rows[i]["name"].ToString()
+ "\n\n5.Type = " + ds.Tables[0].Rows[i]["type"].ToString()
+ "\n\nTIME :- " + current.ToString() + "",
"Message Box", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
Now, each time when i provide a new search parameters in the TextBox and click the button3 button the results is shown in the DataGridView with LinkLabel. When i click the LinkLabel a MessageBox pops-up but its repetition increments by 1 when i provide new search parameters in the TextBox and get new data in my DataGridView according to the search parameters. The number of MessageBox increases with number of time i search.
So anyone can please tell me that how to show MessageBox only for once when i click the LinkLabel even after loading the DataGridView by providing different parameters or search using my textbox.
Your message box shows multiple times because:
You put your message box in a loop. Call the message box only once and pass it what you need to show. If you want to show multiple messages, you can put messages in separated lines in message box.
Also you are adding CellContentClick each time you load data. Add the handler once. You can move the code that assign the handler to event, to your form load event.
Also to check if the clicked cell is the one that you want:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//Check if the clicked cell is your link label column (at index =3)
if(e.ColumnIndex == 3 && e.RowIndex>=0)
{
//e.RowIndex is the index of clicked row
//Use this.dataGridView1.Rows[e.RowIndex] to find the clicked row.
}
}
To set the text for the link label column, you should manipulate the link label column and creating a link label control is useless, for example if col2 is your link label column:
col2.UseColumnTextForLinkValue = true;
col2.Text="More Information !";

Getting the value of Full-Row Clickable Gridview and Display in Textbox

I have a gridview that loads data from a stored procedure.
OBJECTIVE:
to make the full gridview row clickable by hiding the select column in the gridview - I was able to do this by doing the code below in the RowDataBound event.
Next is when I click a full row in the gridview, I should be able to get the data / values from the row selected and display this in the textboxes in the modal pop up to appear. This is for UPDATING / EDITING FUNCTIONS.
Here's what I have got
protected void grdTenant_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Style["display"] = "none";
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] =
"javascript:setMouseOverColor(this);";
e.Row.Attributes["onmouseout"] =
"javascript:setMouseOutColor(this);";
e.Row.Attributes["onclick"] =
Page.ClientScript.GetPostBackClientHyperlink
(this.grdTenant, "Select$" + e.Row.RowIndex);
e.Row.Attributes.Add("onclick", String.Format("javascript:$find('{0}').show();",ModalEditTenant.ClientID ));
//this line does not work in retrieving row data
IDataRecord dataRow = (IDataRecord)e.Row.DataItem;
txtRPCode.Text = Convert.ToString(dataRow["Retail Partner"]);
}
}
As an alternative, I do this to achieve the second goal but fails to do the first
protected void grdTenant_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = grdTenant.SelectedRow;
txtRPCode.Text = row.Cells[1].Text;
ModalEditTenant.Show();
}
But, this method works only when the select button column is visible and when it is clicked, it fails to do so when the full row is selected.
How can I make the full row select and retrieves the data to textbox successfully (with the select column hidden)
This is how gridview bind the data from the stored procedure datasource.
System.Threading.Thread.Sleep(500);
//DropDownList ddl = (DropDownList)sender;
SqlCommand cmd = new SqlCommand("spTenantList", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Location", ddlSelectLoc.SelectedValue );
try
{
con.Open();
grdTenant.EmptyDataText = "No Records Found";
grdTenant.DataSource = cmd.ExecuteReader();
grdTenant.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
Use FindControl()method.
Instead of txtRetailPartner place your TextBox ID.
txtRPCode.Text = ((TextBox)e.Row.FindControl("txtRetailPartner")).Text;
Use my logic below in RowDataBound event to get DataItem:
protected void grdTenant_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Style["display"] = "none";
if (e.Row.RowType == DataControlRowType.DataRow)
{
IDataRecord dataRow = (IDataRecord)e.Row.DataItem;
txtRPCode.Text = Convert.ToString(dataRow["Retail Partner Code"]);
}
}
I have found the answer based on what is to achieved. Using my current codes posted as question , Just remove the one line code there and it will work
protected void grdTenant_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Style["display"] = "none";
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] =
"javascript:setMouseOverColor(this);";
e.Row.Attributes["onmouseout"] =
"javascript:setMouseOutColor(this);";
e.Row.Attributes["onclick"] =
Page.ClientScript.GetPostBackClientHyperlink
(this.grdTenant, "Select$" + e.Row.RowIndex);
}
}
This line is removed:
//This is no longer needed as it will make the onselectedindexchanged event ineffective as this will be run first.
e.Row.Attributes.Add("onclick", String.Format("javascript:$find('{0}').show();",ModalEditTenant.ClientID ));
protected void grdTenant_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = grdTenant.SelectedRow;
txtRPCode.Text = row.Cells[1].Text;
ModalEditTenant.Show();
}
And everything will work as expected.

How to change the default value of a data grid view combo box column with selected value from itself

i have a data grid view combo box column in my data grid view. On on load event of form i am loading the companies name in combo box column and through cell formatting event i am giving the default value to data grid view combo box column.
Now if i select different value from combo box column it does not get reflected. means only default value is there.
My code for on load and cell formatting is
public void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
SqlConnection c = new SqlConnection();
c.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='D:\\Documents\\Visual Studio 2008\\Projects\\Accounts\\Accounts\\Database1.mdf';Integrated Security=True;User Instance=True";
c.Open();
if (e.ColumnIndex == 1 && Viewcashvoucher.mk != "")
{
string mky = Viewcashvoucher.mk;
string q = "select * from lgr where main_key ='" + mky + "'";
SqlCommand cmd = new SqlCommand(q, c);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
e.Value = dr["account_n"].ToString();
}
}
c.Close();
}
and on load event is
private void Cash_Voucher_Load(object sender, EventArgs e)
{
string mky = Viewcashvoucher.mk;
SqlConnection c = new SqlConnection();
c.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='D:\\Documents\\Visual Studio 2008\\Projects\\Accounts\\Accounts\\Database1.mdf';Integrated Security=True;User Instance=True";
c.Open();
string q = "select max(date) from lgr ";
SqlCommand cmd = new SqlCommand(q, c);
SqlDataReader rd = cmd.ExecuteReader();
try
{
if (rd.Read())
{
DateTime date = rd.GetDateTime(0);
if (date != null)
{
tbdate.Text = date.ToShortDateString();
}
}
}
catch (Exception ex)
{
tbdate.Text = DateTime.Now.ToShortDateString();
}
c.Close();
c.Open();
string q1 = "select account_n from master";
SqlCommand cmd1 = new SqlCommand(q1, c);
SqlDataReader rd1 = cmd1.ExecuteReader();
DataGridViewComboBoxColumn acname = dataGridView1.Columns[1] as DataGridViewComboBoxColumn;
while (rd1.Read())
{
acname.Items.Add(Convert.ToString(rd1["account_n"]));
}
}
actually i am using same data grid view for insert and update operation. i want that as user select different value from combo box list the default value should be replaced by selected one.
thanks in advance...
you can also bind the DataBindingComplete event. The only difference in previous and this answer is #Junaith bind the RowAdded event mean it will call the function every time you add the row. and here in mycase I bound DataBindingComplete event which will fire after the grid is full loaded mean this will call only once and that time it will check the all the checkbox in first column of the grid for all the lines.
mygrid.DataBindingComplete +=
new DataGridViewBindingCompleteEventHandler(mygrid_DataBindingComplete);
then and you have to define a function name as mygrid_DataBindingComplete
private void mygrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridView temp = (DataGridView)sender;
foreach (DataGridViewRow rw in temp.Rows)
{
// here 0 indicating the checbox column is the first column in grid
// first column so index would be 0. true will check the checkbox
rw.Cells[0].Value = true;
}
}
CellFormatting event handler is not the right place to set the default value. CellFormatting occurs whenever the content of the cells needs to be formated for display. Whenever you the change the value in the combobox and accept the value, this event is raised and the default value code resets the user selection.
In DataGridView.RowsAdded you could set the defalut value for the combobox cell for the newly added row(s)
Sample Code:
void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
for (int i = e.RowIndex; i < (e.RowIndex+e.RowCount); i++)
{
dataGridView1.Rows[i].Cells[comboboxcolumn_index].Value = defaultvalue;
}
}
hai you can Just use this on RowAdded Event or DataGridview comboboxcolumn creation time. It will Set the Default Value
comboboxcolumn_Name.DefaultCellStyle.NullValue = "Please Select";
void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
for (int i = e.RowIndex; i < (e.RowIndex+e.RowCount); i++)
{
comboboxcolumn_Name.DefaultCellStyle.NullValue = "Please Select";
}
}

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.

Categories

Resources