How to clear the gridview,literal and panel values? - asp.net

I have a textbox called customer id and if the id is not valid, it should display a warning message and needs to go back to the main page where the user retries entering Id again. It works fine if the ID is valid. If the entered Id is invalid, panel and gridview are updating with some random values. How can I clear them? Any suggestions.
DataTable dt = oRecord.GetCustomerName(sId);
if (dt.Rows.Count == 0)
{
// making panel and gridview visible false does not work.
pnlDetails.visible = false;
gvInfo.visible= false
pnlSuccess.Visible = false;
btnOk.Visible = false;
txtId.Text = string.Empty;
txtIdentifier.Focus();
ViewState["sId"] = string.Empty;
}

You should not set visible false as it will be setting controls to invisible along with existing data but data is available and bind with these controls in memory. you should clear content of these controls to empty or null.
DataTable dt = oRecord.GetCustomerName(sId);
if (dt.Rows.Count == 0)
{
gvInfo.DataSource = null;
txtId.Text = string.Empty;
txtIdentifier.Focus();
ViewState["sId"] = string.Empty;
}

Related

Rows added to gridview don't persist when save event is triggered

I have a gridview on my webpage that can have rows added dynamically. There is a for loop that adds the rows like this:
protected void AddNewJob(object sender, EventArgs e)
{
for(int i = 0; i < Convert.ToInt32(newJobCount.Text);i++)
{
TableRow tr = new TableRow();
tr.Cells.Add(ServicesDDL("-- Select Service Type --"));
tr.Cells.Add(JobsDDL("-- Select Job Type --"));
tr.Cells.Add(TextBoxCell());
tr.Cells.Add(TextBoxCell());
tr.Cells.Add(TextBoxCell());
assetTable.Rows.Add(tr);
}
}
After the rows are added and changed from their default values the rows are looped through and data is saved to the database. I'm having problems getting the rows added to the gridview to persist and exist on the gridview when the page's save event is triggered. That code looks like this:
foreach (TableRow row in assetTable.Rows)
{
if (isFirst)
{
isFirst = false;
continue;
}
DropDownList service = (DropDownList)row.Cells[0].Controls[0];
string assetText = service.SelectedItem.Value;
DropDownList jobDescription = (DropDownList)row.Cells[1].Controls[0];
string serialText = jobDescription.SelectedItem.Value;
TextBox equipmentCount = (TextBox)row.Cells[2].Controls[0];
string leaseText = equipmentCount.Text;
TextBox jobSize = (TextBox)row.Cells[3].Controls[0];
string originText = jobSize.Text;
TextBox serialNo = (TextBox)row.Cells[4].Controls[0];
string deliveryText = serialNo.Text;
string oNo = orderNo.Text;
if (assetText != "0" && serialText != "0")
{
APICallClass.Job j = new APICallClass.Job();
j.JobTypeID = Convert.ToInt32(serialText);
j.serviceID = Convert.ToInt32(assetText);
j.equipment = leaseText;
j.jobSize = originText;
j.serialNumbers = deliveryText;
j.orderID = Convert.ToInt32(global.GlobalID);
APICallClass.API.AddJob(j, Session["Variable"].ToString());
}
}
When the code pasted above runs, it only sees the rows that are pulled in from the database. I think my problem could be fixed by calling something like .databind() somewhere that I'm not, but I've tried a few places and they have not fixed the problem.
Thanks in advance for any help, and helping me become a more robust ASP.NET developer.
When a GridView is DataBind()-ed, the contents of the GridView are "rebuilt" based on the the GridView's DataSource. If you need the new row to stay in the GridView, either do not call DataBind() after the new row is added, or ensure that the contents of your new row are in the GridView's DataSource before future calls to DataBind().
In a page I wrote once I had a similar situation and did the latter. The data for the initial rows was pulled from the database on the first page load and persisted in ViewState. As the user added, removed, and reordered rows in the GridView, the page just changed the data in ViewState and re-DataBind()ed the GridView.

RowClick and find does not work in Devexpress XtraGrid Sub Levels

I have populated a XtraGrid view with two leves.I can work with main level fine but when I want to find in second level by code or even I add an Event like OnRowClick or sth like that for sublevels it does not work.Does any one has my problems?
for example the name of gridview in sublevel is GridProperty..this code does not work
[C#]
GridProperty.ApplyFindFilter(bar_edit_search.EditValue.ToString());
or even events does not fire
[C#]
private void GridProperty_RowClick(object sender, RowClickEventArgs e){}
Here is how I populate my gridview
string owner = "SELECT [OBJECTID],[Name] ,[Family] ,[Father] ,[shenasname],[Dftarche] ,[Birthday] ,[education] ,[home_address] ,[farm_address] ,[ensurance] ,[phone] ,[home_number] ,[owner_id],[sodor] ,[shahr],[bakhsh] ,[dehestan] ,[rosta] ,[kodPosti] FROM [dbo].[OWNER]";
string strConnString = Properties.Settings.Default.land_gisConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
SqlCommand command = new SqlCommand(owner, con);
SqlDataAdapter adapter = new SqlDataAdapter();
dsMain = new System.Data.DataSet();
adapter.SelectCommand = command;
adapter.Fill(dsMain, "First Table");
dsMain.Tables.Add(iFeatureSet.DataTable.Copy());
adapter.Dispose();
command.Dispose();
DataRelation newRelation = new DataRelation("املاک شخصی", dsMain.Tables["First Table"].Columns["owner_id"], dsMain.Tables["Table1"].Columns["owner_ID"]);
dsMain.Relations.Add(newRelation);
}
GridAttrebuteTable.DataSource = dsMain.Tables[0];
GridAttrebuteTable.ForceInitialize();
GridOwners.Columns["shahr"].Visible = false;
GridOwners.Columns["bakhsh"].Visible = false;
GridOwners.Columns["dehestan"].Visible = false;
GridOwners.Columns["rosta"].Visible = false;
GridOwners.Columns["kodPosti"].Visible = false;
GridOwners.Columns["sodor"].Visible = false;
GridOwners.Columns["sodor"].OptionsColumn.AllowShowHide = false;
GridOwners.Columns["shahr"].OptionsColumn.AllowShowHide = false;
GridOwners.Columns["bakhsh"].OptionsColumn.AllowShowHide = false;
GridOwners.Columns["dehestan"].OptionsColumn.AllowShowHide = false;
GridOwners.Columns["rosta"].OptionsColumn.AllowShowHide = false;
GridOwners.Columns["kodPosti"].OptionsColumn.AllowShowHide = false;
SplashScreenManager.CloseForm();
There are no problems with sublevels. You must check the following:
0. For ColumnView.ApplyFindFilter method check the ColumnView.OptionsFind.FindFilterColumns property. According to documentation:
If the FindFilterColumns property is set to "*", the Find Panel
performs searches against all visible columns.
To explicitly specify search columns, set the FindFilterColumns
property to a string consisting of the corresponding field names
delimited by a semicolon (without space characters):
"Name;Value;Description".
So, if your FindFilterColumn property is set to wrong value then ApplyFindFilter method will not work.
1. For GridView.RowClick event according to documentation:
The RowClick event will not fire when clicking on a row cell, if data
editing is enabled and the ColumnViewOptionsBehavior.EditorShowMode
property is set to MouseDown (and to Default if multiple row selection
is disabled).
So, check your ColumnView.OptionsBehavior.EditorShowMode property and set it to EditorShowMode.Click.
2. Check the GridLevelNode.RelationName. It must be equal to RelationName in your underlying DataSource:
DataRelation newRelation = new DataRelation("املاک شخصی", dsMain.Tables["First Table"].Columns["owner_id"], dsMain.Tables["Table1"].Columns["owner_ID"]);
//...
gridControl.LevelTree.Nodes[0].RelationName = "املاک شخصی";

C#/ASP.Net - Extract bit value of column in a gridview

I have a gridview that is SQL bound. In some of the columns there are bit values. When I use C# to get the values into the gridview, checkboxes are displayed. I need to extract the value of that column into text.
SqlConnection sConnection = new SqlConnection(MyConnectionString);
SqlCommand sCommand = new SqlCommand();
using (sConnection)
{
sCommand.Connection = sConnection;
sCommand.CommandText = "MyStoredProcedure";
sCommand.CommandType = CommandType.StoredProcedure;
sCommand.Connection.Open();
SqlDataReader reader = sCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
gridView.DataSource = reader;
gridView.DataBind();
}
for (int i = 0; i < gridView.Rows.Count; i++)
{
ListBox1.Items.Add(gridView.Rows[i].Cells[3].Text);
}
}
}
The gridview column data type is 'bit'. I do not have access to the database or stored procedure to change anything there. I need to somehow extract the '0' or '1' value, but when I do it like above, the text is blank.
I also tried to use 'GetOrdinal'. It returned a True/False value from the database, but I could not figure out how to get the value for each item in the gridview.
if (!reader.IsDBNull(reader.GetOrdinal("MyColumn1")))
{
ListBox1.Items.Add(reader.GetOrdinal("MyColumn1").ToString());
}
General overview:
You need to be able to find the CheckBox that's generated and get the value of it's "Checked" property.
To do this, you need to be able to use the FindControl() method on the GridViewRow.
To use FindControl, the CheckBox needs a predictable name.
To get a predictable name, you need to have that column be a TemplateColumn so that you can specify the name of the CheckBox in the markup on the ASPX page.
There's a full working set of code here: http://www.codeproject.com/Articles/25056/The-RIGHT-Way-to-Use-Checkboxes-in-a-NET-Repeater
This shows the code for a Repeater, but it's the same principle and general code for any DataBound control.
The code below should work with modifications to match your DB names:
<asp:TemplateField>
<ItemTemplate >
<asp:checkbox id="MyColumnNameCheckbox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
string defaultvalue = "0"; // To be used to display the value of the original bit field.
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkBx = (CheckBox)row.FindControl("MyColumnNameCheckbox");
if (chkBx != null && chkBx.Checked)
{
defaultvalue = "1";
}
}
I was able to figure it out. Thanks, David Stratton, for pointing me in the right direction.
I did it by assigning an id to the dynamically created control first. then did the FindControl()...
Control ctrl = GridView1.SelectedRow.Cells[4].Control[0];
ctrl.ID = "ctrl";
Boolean result = Convert.ToBoolean(((Checkbox)GridView1.Rows[0].Cells[4].FindControl("ctrl")).Checked);
TextBox1.Text = result.ToString();
This returns a value of "True" or "False"...
Thanks again.
Another way to resolve it:
bool result = (GridView1.SelectedRow.Cells[4].Control[0] as Checkbox).Checked;
TextBox1.Text = result.ToString();
it resolve the problem with less code :)

Mutliple dropdowns and values on the Paging

I have a GridView and I populate it via a DATASET . Three of its columns are three DropDownLists and AllowPaging is set to true for the grid view. My problem is when I choose a value on anyone of the ddl and click on serach button i get the data on the gridview which will have paginig, but when i click on the second page i loose teh filtered calue onthe drop down and i again get the earlier dataset.
Is there any way/idea to persist the selected values? Thanks for your help.
Please can you help me with this. if i am not filtering anyone of teh dropdown and then clicking on the second or third page i get the relevant data of that particular page. teh only problem is when i have a value selected on the dropdown .
code:
button click:
{
string _strBU = BUDropDownList.SelectedValue;
string _strOU = OUDropDownList.SelectedValue;
string _strPortalID = !string.IsNullOrEmpty(TxtEmpPortalID.Text.Trim()) ? TxtEmpPortalID.Text.Trim() : string.Empty;
string _strRU = RUDropDownList.SelectedValue;
string _strMngrPortalID = System.Web.HttpContext.Current.User.Identity.Name.ToString();
_strMngrPortalID = _strMngrPortalID.Substring(4, 6);
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = "server=;uid=;pwd=;database=HROrgchartDB";
sqlConnection.Open();
SqlCommand sqlEmployeeDetailsCommand = new SqlCommand();
sqlEmployeeDetailsCommand.Connection = sqlConnection;
sqlEmployeeDetailsCommand.CommandText = "EmployeeSearch";
sqlEmployeeDetailsCommand.CommandType = CommandType.StoredProcedure;
sqlEmployeeDetailsCommand.Parameters.Add(new SqlParameter("#BU", SqlDbType.VarChar, 50)).Value = _strBU;
sqlEmployeeDetailsCommand.Parameters.Add(new SqlParameter("#OU", SqlDbType.VarChar, 50)).Value = _strOU;
sqlEmployeeDetailsCommand.Parameters.Add(new SqlParameter("#PORTALID", SqlDbType.VarChar, 6)).Value = _strPortalID;
sqlEmployeeDetailsCommand.Parameters.Add(new SqlParameter("#RU", SqlDbType.VarChar, 50)).Value = _strRU;
sqlEmployeeDetailsCommand.Parameters.Add(new SqlParameter("#ManagerPortalID", SqlDbType.VarChar, 6)).Value = _strMngrPortalID;
SqlDataAdapter da = new SqlDataAdapter(sqlEmployeeDetailsCommand);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds != null)
{
// gvAddorRelease.Visible = true;
gridReportees.DataSource = ds;
Cache["D2"] = ds;
gridReportees.PageIndex = 0;
gridReportees.DataBind();
}
else
{
}
sqlConnection.Close();
}
}
event for paging :
gridReportees_PageIndexChanging:
{
gridReportees.PageIndex = e.NewPageIndex;
DataSet ds = new DataSet();
ds=(DataSet)Cache["D2"];
gridReportees.DataSource= ds;
gridReportees.DataBind();
}
Problem:
When you click on the next page, dropdown also rebinds due to which there selected index changed to 0.
Solution:
When you press the search button at that time you have to save the selectedvalues of the 3 dropdownlists. the dropdowns are present inside your gridview,so first you have to get the gridview row index. You can get the row index from gridveiw_selectedindexchange event. [Hint]
ViewState["svalue1"] = ((DropDownList) gv.Rows[index].FindControl("dropdownlistID")).Text;
// also get the selected values of other 2 dropdowns
Now after getting the selectedvalues you have to set the dropdwonlist.selected value to the values which we have saved in the ViewState.
gridReportees_PageIndexChanging()
{
// After binding the grid
// in this metho set the dropdown seleted value
// example get a reference of your dropdown
DropDownList ddl1 = (DropDownList) gv.Rows[index].FindControl("dropdownlistID");
ddl.SelectedValue = ViewState["svalue1"].ToString();
// follow the same steps for other 2 dropdownlists
}
Hope that it works for you.

gridview sorting problem in paging

In gridview
when i go to nextpage(page2) and clicked on header to sort, it is sorting all the data. i need to sort only the data in page2
here is my code
DataTable dataTable = ViewState["HospAcc"] as DataTable;
if (dataTable != null)
{
DataView dv = new DataView(dataTable);
dv.Sort = string.Format("{0} {1}", e.SortExpression, Direction);
Direction = (Direction == "ASC") ? "DESC" : "ASC";
//Bind resutls
gvHospAcc.DataSource = dv;
gvHospAcc.DataBind();
}
and one more thing is when i go to second page my sort is getting collapsed
Thank you
How are you getting your data into the gridview? You could manually page the data that goes into the gridview; that way, when you click on the header, it will only sort the data on that page, since there's no other data besides that.

Resources