0
我有一個上傳功能,它會將csv文件上傳到gridview。我想檢查Gridview的第一列是否有重複的記錄記錄。如果有,我想顯示一條錯誤消息,如「重複記錄!」並使一個名爲btnimport1的按鈕不可見。誰能幫我?這是我的代碼至今:檢查Gridview中的重複項並顯示錯誤消息(如果存在)?
//A method to display errors in the gridview
private string ErrorMessage(string input)
{
{
//if there are null values, error message will be displayed.
if (!string.IsNullOrEmpty(input))
return input;
//making the button invisble, so that the user will be forced to cancel import and re-upload new file
BtnImport1.Visible = false;
}
return "No value entered!";
}
protected void btnUpload_Click(object sender, EventArgs e)
{
//get the uploaded file name
string strFileNameOnServer = fileUpload.PostedFile.FileName;
//get the uploaded file's extension
string fileExt =
System.IO.Path.GetExtension(fileUpload.FileName);
// if the uploaded file is not null and the file extension is csv, do the try
if (fileUpload.PostedFile != null && fileExt == ".csv")
{
try
{
fileUpload.PostedFile.SaveAs(Server.MapPath("~/Uploads"));
//to display the contents of file
Label1.Text = "File name: " +
fileUpload.PostedFile.FileName + "<br>" +
fileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
fileUpload.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = "Error saving <b>" + strFileNameOnServer + "</b><br>. " + ex.Message;
}
//to make the import and cancel import button visible so that users can either choose to import or cancel
BtnImport1.Visible = true;
Cancel.Visible = true;
//to make the upload button invisible
fileUpload.Visible = false;
btnUpload.Visible = false;
}
else
{
//if the user does not select anything or the file is extension is not .csv, the error message will be displayed
Label1.Text = "Error - a file name must be specified/only csv files are allowed";
return;
}
// to read all lines of the posted csv file and put the lines in the grid view
var data = File.ReadAllLines(Server.MapPath("~/Uploads"))
// to split the lines according to commas
.Select(line => line.Split(','))
.Select(columns => new { GuestID =ErrorMessage(columns.Length<=8?"":columns[0]), IC_No = ErrorMessage(columns[1]), Grouping = ErrorMessage(columns[2]), Remarks = ErrorMessage(columns[3]), GuestName = ErrorMessage(columns[4]), Class_Group = ErrorMessage(columns[5]), Staff = ErrorMessage(columns[6]), Attendance_Parents_Only = ErrorMessage(columns[7]), Registration = ErrorMessage(columns.Length<=8?"":columns[8]) });
myGridView.DataSource = data;
myGridView.DataBind();
}
我只想在第一列,這是列0感謝重複檢查並顯示錯誤信息!
我認爲這將是更好的爲您管理您的數據插入和更改,以便首先不會出現重複記錄 - 而不是在事實之後顯示錯誤。 –
上傳實際上允許用戶上傳,因此,我不能限制他們,這就是爲什麼我需要錯誤檢查 – Mark20